Handling `Result<T>` & smart casting - t...
# compiler
r
Handling
Result<T>
& smart casting - the first way would be nice, but
Result
doesn't seem to be implemented that way. Is the second answer how to do it? https://chat.openai.com/share/ce159d0a-ec14-405e-972c-5f1936461e7b
First way:
Copy code
fun handleResult(result: Result<Int>) {
    when (result) {
        is Result.Success -> {
            // Smart cast to Result.Success
            val value = result.getOrNull() // Or just 'result.value' in Kotlin 1.5+
            println("Success with value: $value")
        }
        is Result.Failure -> {
            // Smart cast to Result.Failure
            val exception = result.exceptionOrNull()
            println("Failure with exception: $exception")
        }
    }
}
Second answer:
Copy code
fun handleResult(result: Result<Int>) {
    if (result.isSuccess) {
        // Safe to get the value
        val value = result.getOrNull()
        println("Success with value: $value")
    } else if (result.isFailure) {
        // Safe to get the exception
        val exception = result.exceptionOrNull()
        println("Failure with exception: $exception")
    }
}