Non-null Assertions

A second approach to the problem of nullable types is to claim you have special knowledge that the reference in question isn’t null.

This claim is achieved using the double exclamation point, !!, called the non-null assertion. If this looks alarming, it should: believing that something can’t be null is the source of most null-related program failures (the rest come from not realizing that a null can happen).

x!! means “forget the fact that x might be null—I guarantee that it’s not null.” x!! produces the reference if x isn’t null; otherwise it throws an exception:

// NonNullAssertions/NonNullAssert.kt import atomictest.* fun main(args: Array<String>) { val s1: String? = "abc" s1!! eq "abc" val s2: String? = null // Compiles, but produces a // KotlinNullPointerException: capture { val s3: String = s2!! } eq "KotlinNullPointerException" }

The definition val s3: String = s2!! tells the compiler to ignore what it thinks it knows about s2 and just assign it to s3, which is a non-nullable reference. Fortunately, there’s run-time support which throws an exception when it turns out s2 is null.

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.