concept Result in category kotlin

appears as: Result, Result
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

What you need is a type representing either data or an error. As this type generally represents the result of a computation that might have failed, you’ll call it Result. It’s similar to the Option type, except the subclasses are named Success and Failure as shown in the following listing. As you can see, this class is much like the Option class with the additional stored exception.

Listing 7.2 The Result class
import java.io.Serializable

sealed class Result<out A>: Serializable {    #1  

    internal    #2  
    class Failure<out A>(
        internal val exception: RuntimeException):    #3  
                                         Result<A>() {
        override fun toString(): String = "Failure(${exception.message})"
    }

    internal   #3  
    class Success<out A>(internal val value: A) :
                                         Result<A>() { 
        override fun toString(): String = "Success($value)"
    }

    companion object {

        operator fun <A> invoke(a: A? = null): Result<A>
            = when (a) {
               null -> Failure(NullPointerException())    #6  
               else -> Success(a)
            }

        fun <A> failure(message: String): Result<A> =
            Failure(IllegalStateException(message))    #7  

        fun <A> failure(exception: RuntimeException): Result<A> =
            Failure(exception)    #8  

        fun <A> failure(exception: Exception): Result<A> =
            Failure(IllegalStateException(exception))   #9    
    }
}

#1   The Result class takes only one type parameter, corresponding to the success value.
#2   Constructors are internal.
#3   The Failure subclass contains a RuntimeException.
#6   If a Result is constructed with a null value, you immediately get a Failure.
#7   If a Failure is constructed with a message, it’s wrapped into a RuntimeException (more specifically, the IllegalStateException subclass).
#8   If constructed with a RuntimeException, it’s stored as is.
#9   If constructed with a checked exception, it’s wrapped into a RuntimeException.

To compose Result, you’ll need the same functions that you defined in the Option and Either classes, with minor differences.

Define a mapFailure function that takes a String as its argument and transforms a Failure into another Failure, using the string as its error message. If the Result is Empty or Success, this function should do nothing.