Any good way or Contract to handle value or error on Kotlin.Result

#1

when value is Failure, there is an error, when value isn’t Failure, there is a value, in other words, value and error must not exist at the same time, one of them must be null. I didn’t find a good way to handle kotlin.Result, logically lambda onFailure or onSuccess both can be called together, there is no Contract on them that exactly one will be called.

Due to my shitty English, If you don’t understand what I’m talking about, read code below.

I have my custom Result, it works well to me by using when block.

sealed class Result<out T : Any> {
    object Loading : Result<Nothing>()
    class Value<out T : Any>(@JvmField val value: T) : Result<T>()
    class Error(@JvmField val error: Throwable) : Result<Nothing>()
}

    val r: Result<String> = someTodo()

    // only one branch will be called exactly once, that's what I need.
    when (r) {
        is Result.Loading -> {
            /* singleton object for loading state */
        }
        is Result.Error -> {
            /* r.error not null, very happy to use it */
        }
        is Result.Value -> {
            /* r.value not null and must be String type here, very happy to use it */
        }
    }