Extensions for Nullable Types

Sometimes it’s not what it looks like.

Here we hope to prevent confusion and adjust intuition around the syntax for safe calls. When you see s?.foo(), you expect that s is nullable since otherwise the call would be s.foo(). Similarly, when you see s.foo(), you suppose that s has been proven non-nullable because the compiler allows the dereference without a safe call or programmatic check. However, the latter isn’t true.

The Kotlin standard library provides useful extension functions for Strings, including isNullOrEmpty() and isNullOrBlank(). These names suggest that they are for nullable types:

// NullableExtensions/StringIsNullOr.kt import atomictest.eq fun main(args: Array<String>) { val s1: String? = null s1.isNullOrEmpty() eq true s1.isNullOrBlank() eq true val s2 = "" s2.isNullOrEmpty() eq true s2.isNullOrBlank() eq true val s3: String = " \t\n" s3.isNullOrEmpty() eq false s3.isNullOrBlank() eq true }

isNullOrEmpty() checks that the receiver string is either null or empty, and isNullOrBlank() performs the same check and allows the string to consist solely of whitespace characters, including tabs (\t) and newlines (\n).

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

Previous          Next

©2018 Mindview LLC. All Rights Reserved.