concept Result in category kotlin
appears as: Result, Result

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 theOptiontype, except the subclasses are namedSuccessandFailureas shown in the following listing. As you can see, this class is much like theOptionclass with the additional stored exception.Listing 7.2 The
Resultclassimport 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 theOptionandEitherclasses, with minor differences.