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

Updated on: 01-Mar-2022

941 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements