Safe Call ?. and Elvis ?: in Real Code
Chain safe calls and provide fallback values using the Elvis operator.
Two Operators, Big Impact
The safe call ?. calls a member only if the receiver is non-null. The Elvis operator ?: provides a fallback when the left side is null.
Safe Call Basics
x?.member evaluates to null if x is null; otherwise it accesses member normally.
fun main() {
val name: String? = "Kotlin"
val len: Int? = name?.length
println(len) // 6
val nope: String? = null
println(nope?.length) // null
}All lessons in this course
- Nullable Types and the ? Modifier
- Safe Call ?. and Elvis ?: in Real Code
- let, also, and run with Nullable Receivers
- !! Operator: When and Why to Avoid It