- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why can't 'kotlin.Result' be used as a return type?
Result is a Serializable class in Kotlin. The function definition looks like this −
class Result<out T> : Serializable
This class has two properties − "isFailure" and "isSuccess".
As per the documentation, Result<T> cannot be used as a direct return type of Kotlin function. However, in this article, we will see how we can use this Result in our Kotlin programs.
// ERROR: 'kotlin.Result' cannot be used as a return type fun findUserByName(name: String): Result<User> fun foo(): Result<List<Int>> // ERROR fun foo(): Result<Int>? // ERROR var foo: Result<Int> // ERROR
Example – Kotlin.Result
sealed class myInterFace<out Success, out Failure> data class Success<out Success>(val value: Success) : myInterFace<Success, Nothing>() data class Failure<out Failure>(val reason: Failure) : myInterFace<Nothing, Failure>() fun myMethod(string : String) : myInterFace<String, Exception> { return if (string.isEmpty()) { Failure(Exception("Error in the process")) } else { Success(string) } } fun main(args : Array<String>) { when(val result = myMethod("")) { is Success -> println(result.value) is Failure -> println(result.reason) } }
Output
On execution, it will produce the following output −
java.lang.Exception: Error in the process
Advertisements