Kotlin Smart casts


If the compiler can infer that an object can't be null at a certain point, you don't have to use the special operators anymore:

var string: String? = "Hello!"
print(string.length)  // Compile error
if(string != null) {
    // The compiler now knows that string can't be null
    print(string.length)  // It works now!

Note: The compiler won't allow you to smart cast mutable variables that could potentially be modified between the null-check and the intended usage.

If a variable is accessible from outside the scope of the current block (because they are members of a non-local object, for example), you need to create a new, local reference which you can then smart cast and use.