8 ms·
I'm a little confused by something. I wouldn't have expected his/her example code to compile: fun divide(dividend: Int, divisor: Int): Try<Int, String> =
by ragnese 7y ago
I'm a little confused by something. I wouldn't have expected his/her example code to compile:
fun divide(dividend: Int, divisor: Int): Try<Int, String> =
when (divisor) {
0 -> Try.Err("Cannot divide by zero!")
else -> Try.Ok(dividend / divisor)
}
The first branch of `when` is of type `Try<Nothing, String>`, the second branch is `Try<Int, Nothing>`, and the return value is supposed to be `Try<Int, String>`. None of those line up...
How is that possible? Does the compiler do some magic for the `Nothing` type? The definition looks pretty damn simple:
public class Nothing private constructor()
- greiskul 7y agoIt's not possible in Kotlin to have an instance of Nothing, and the compiler does some magic for the Nothing type, in that it can be converted to any other type in the system (so it's like the opposite of the Any type). This allow code patterns like: ''' val personName = person.name ?: throw IllegalArgumentException("Name required") ''' Where the type of personName is now String, cause if name was null it would throw an exception (and the type of a throw expression is Nothing).
- lmm 7y agoNothing is (magically) a subtype of every type, and Try is covariant in both its parameters (Kotlin has its own non-standard terminology for variance that I can't remember, but what it really means is covariant).