Trying to understand why Kotlin's smart cast doesn't trigger for a fairly simple use case:
val x: Int? = 1
val notNull: Boolean = x != null
if (notNull) {
val y: Int = x // fails to smart cast
}
However it works if we remove the intermediate val
:
val x: Int? = 1
if (x != null) {
val y: Int = x // smart cast works
}
val
essentially defines a final
value, so I don't see the reason why the first version wouldn't work.
For the record Java's analog to this (https://github.com/uber/NullAway) also fails for such use cases so there might be some underlying complication that makes such deductions impossible?