Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a constructor can't return null, why do I need to type-check after initialization?

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?

like image 845
Rollie Avatar asked Feb 26 '26 02:02

Rollie


1 Answers

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.

like image 138
Michael Piefel Avatar answered Feb 28 '26 14:02

Michael Piefel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!