Safe Calls & The Elvis Operator

Kotlin provides convenient operations for handling nullability.

Nullable types come with numerous restrictions. You can’t simply dereference an identifier of a nullable type:

// SafeCallsAndElvis/DereferenceNull.kt fun main(args: Array<String>) { val s: String? = null // Won't compile: // s.length // [1] }

Uncommenting [1] produces a compile-time error: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?.

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



Previous          Next

©2018 Mindview LLC. All Rights Reserved.