So given:
val c: Circle? = Circle(5)
println(c.circumference())
Kotlin compiler complains that circumference() can't be called because c could be null. Is that true? Or is the compiler a dirty no good liar?
The compiler is a dirty no good liar. There is no way that c could be null. Since c is a val, there is no (legal) way for it to change its value, for instance in another thread, and it is provable that c cannot be null. Consider the slighty simpler case (no external classes required):
val i1: Int? = 42
val i2: Int = i1
Even this will not compile. However, the following will:
val i1: Int? = 42
checkNotNull(i1)
val i2: Int = i1
Here, the checkNotNull (from PreConditions in the standard library) performs some null check, and the compiler will create a smart cast. I assume JetBrains could fix the compiler, but there would be little use outside of demonstration purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With