Any one please explain this code. Thanks
# announcements
m
Any one please explain this code. Thanks
r
what do you don't understand? (also would be great if you posted the code directly next time...)
s
improvement: since the code assumes that the Success.data should be non-null in order for the Result to count as succeeded, the generic type should be restricted to (non-nullable)
Any
:
Copy code
data class Success<T:Any>...
👍 3
I fixed it for you
Copy code
sealed 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-cast
K 4
Nothing
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.
👌 1