user1443721
user1443721

Reputation: 1260

Nullable variable in Kotlin

I have this code example.

var nullAbleName: String? = null 
var v = "I cannot be null"
//!    v = nullAbleName      // mismatch

nullAbleName = "abc"
v = nullAbleName         // Now OK. 

nullAbleName is a variable, and its value should be determined in run-time. What is the logic that 2nd assignment of v is OK? Is it that I am lucky because the compiler happens to know the nullAbleName has a value?

Upvotes: 1

Views: 612

Answers (1)

Tenfour04
Tenfour04

Reputation: 93511

This is called smart-casting. The compiler is able to see that the local variable was most recently set to an explicit String, so it treats it as non-null. You may notice that the assignment is colored/highlighted differently by the IDE to show that is employing smart-casting.

This only works with local variables that have not been captured by a closure that modifies them (for instance, creating a callback instance that modifies the value of the local variable). So properties are ineligible for smart casting because they aren't local variables (and could be changed elsewhere) and local variables captured in closures aren't eligible (because they could be changed elsewhere by the closure).

Upvotes: 6

Related Questions