Null values can be a pain to deal with in any programming language. In Kotlin, the Elvis operator provides a concise and safe way to handle null values.
The Elvis operator is a null-safe operator that returns the non-null value of its operand or a default value if the operand is null. The Elvis operator is written as follows:
val result = operand ?: defaultValue
If the operand is not null, the Elvis operator returns it. If the operand is null, the Elvis operator returns the default value.
The Elvis operator is made up of two parts: the null-safe operator (?.
) and the Elvis operator (?:
).
The null-safe operator (?.
) is used to safely access a member of a nullable object. If the object is null, the null-safe operator returns null instead of throwing a NullPointerException.
The Elvis operator (?:
) is used to provide a default value if the operand is null.
The Elvis operator is most commonly used to handle null values in a concise and safe way.
For example, consider the following code:
val list: List<String>? = null
val firstItem = list?.get(0) ?: "Default Value"
In this code, the list
variable is nullable. If list
is null, the firstItem
variable will be set to the default value ("Default Value"). If list
is not null, the firstItem
variable will be set to the first item in the list.
Here are some additional resources for learning more about the Elvis operator: