Elvis Operator
suggest changeIn Kotlin, we can declare a variable that can hold a null reference. Suppose we have a nullable reference a. We can say “if a is not null, use it, otherwise use some non-null value x”:
var a: String? = "Nullable String Value"
Now a can be null. When we need to access a, we need a null check. We can do that with a conventional if...else statement.
val b: Int = if (a != null) a.length else -1
The same choice can be written with the Elvis operator, ?::
val b = a?.length ?: -1
If the expression to the left of ?: (here, a?.length) is not null, the Elvis operator returns it. Otherwise it returns the expression to the right (here, -1). The right-hand side is evaluated only if the left-hand side is null.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents