Safe Calls and Elvis
?. and ?: operators.
Working with Nullables Cleanly
Writing if (x != null) everywhere gets verbose. Kotlin offers two concise operators for nullable values:
- the safe call
?. - the Elvis operator
?:
The Safe Call Operator
The safe call ?. calls a method or reads a property only if the value is not null. Otherwise the whole expression evaluates to null.
No crash, no explicit check.
fun main() {
val name: String? = "Kotlin"
println(name?.length)
}All lessons in this course
- Nullable and Non-Null Types
- Safe Calls and Elvis
- The !! Operator
- Platform Types