Smart-Casting and the Elvis Operator
Explore smart casting for null checks and efficiently set default values with the Elvis operator.
We'll cover the following...
Smart-casting
Smart-casting also works for nullability. Therefore, in the scope of a non-nullability check, a nullable type is cast to a non-nullable type.
Press + to interact
fun printLengthIfNotNull(str: String?) {if (str != null) {println(str.length) // str smart-casted to String}}fun main() {val nullableString: String? = "Hello, Kotlin"val nullString: String? = nullprintLengthIfNotNull(nullableString) // Output: 13printLengthIfNotNull(nullString) // No output (null)}
Smart-casting also works when we use return
or throw
if a value is not null
.
Press + to interact
fun printLengthIfNotNull(str: String?) {if (str == null) returnprintln(str.length) // str smart-casted to String}fun main() {val nullableString: String? = "Hello, Kotlin"val nullString: String? = nullprintLengthIfNotNull(nullableString) // Output: 13printLengthIfNotNull(nullString) // No output (null)}
Utilizing smart-casting, ...