Ivan Brko
04/22/2020, 1:02 PMfun magic(s: String): Either<Exception, String>
val x = magic("2")
val value = when(x) {
is Either.Left -> when (x.a){
is NumberFormatException -> "Not a number!"
is IllegalArgumentException -> "Can't take reciprocal of 0!"
else -> "Unknown error"
}
is Either.Right -> "Got reciprocal: ${x.b}"
}
And above the code, the following is written: You should also notice that we are using SmartCast for accessing Left and Right values.
I expected that to mean that after matching X with Either.Left, the compiler would know that x is of type Exception (and the same for right, but there that x is of type String). Here you still have to call .a or .b to get the value.
So sorry if this is a stupid question, but what exactly is smart casted here and would it be possible to get Kotlin to know that x is of type String after matching it with Right here?Mike
04/22/2020, 1:22 PMwhen, the compiler only knows that x is an Either.
After the is in the when it now knows that the x is more specifically a Left or a Right. So you don't have to do something like is Either.Left -> when ((Left) x).a when you want to use x.thanerian
04/22/2020, 1:53 PMMike
04/22/2020, 2:00 PMthanerian
04/22/2020, 2:05 PMMike
04/22/2020, 2:08 PMpakoito
04/22/2020, 3:06 PMis Either.Left<Throwable> or similar won't workpakoito
04/22/2020, 3:07 PMfold instead, it's the same as whenpakoito
04/22/2020, 3:07 PMpakoito
04/22/2020, 3:08 PMval value = x.fold({ a ->
when (a){
is NumberFormatException -> "Not a number!"
is IllegalArgumentException -> "Can't take reciprocal of 0!"
else -> "Unknown error"
}, { b ->
"Got reciprocal: $b"
})Ivan Brko
04/22/2020, 6:34 PM