Search⌘ K
AI Features

Smart-Casting and the Elvis Operator

Explore Kotlin's smart-casting mechanism and the Elvis operator to handle nullability safely in your code. This lesson helps you learn how to cast nullable types to non-nullable within conditional checks and use the Elvis operator to provide default values, improving code safety and reliability when managing nullable variables.

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.

Kotlin 1.5
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? = null
printLengthIfNotNull(nullableString) // Output: 13
printLengthIfNotNull(nullString) // No output (null)
}

Smart-casting also works when we use return or throw if a value is not null.

Kotlin 1.5
fun printLengthIfNotNull(str: String?) {
if (str == null) return
println(str.length) // str smart-casted to String
}
fun main() {
val nullableString: String? = "Hello, Kotlin"
val nullString: String? = null
printLengthIfNotNull(nullableString) // Output: 13
printLengthIfNotNull(nullString) // No output (null)
}

Utilizing smart-casting, this code demonstrates ...