Mohammad Jahidul Islam
08/05/2021, 6:20 AMRoukanken
08/05/2021, 6:24 AMStephan Schroeder
08/05/2021, 6:31 AMAny
:
data class Success<T:Any>...
Stephan Schroeder
08/05/2021, 6:44 AMsealed class Result<R:Any> {
data class Success<R:Any>(val data: R): Result<R>()
data class Error(val exception: Exception): Result<Nothing>()
}
val Result<*>.succeeded get():Boolean = this is Result.Success
fun <T:Any> Result<T>.successOr(fallback: T): T = when(this) {
is Result.Success -> this.data
else -> fallback
}
So basically you have a sealed class with an extension property and and extension method. Those two could definitely have been defined inside of Result
directly but this way it's easier to see what Result is all (/mostly) about.
• it's debatable if you still need succeeded
since result.succeeded
is only a shorthand for result is Result.Success
which would come with a smart-castStephan Schroeder
08/05/2021, 6:47 AMNothing
is the type on Error
, because Error
doesn't come with any instance of R
. It's a bit of an advanced concept, but Nothing
is assignable to all (non-nullable) types since it doesn't exist anyway to cause troubles at runtime.
It's very elegant once you wrap your head around it.