In Kotlin, the Elvis Operator (?:) is a very useful tool when working with nullable variables. It helps us to provide a default value if an expression returns null. This operator makes our code shorter, cleaner, and safer when dealing with possible null values.
Definition:
Sometimes in Kotlin, we declare variables that can hold null references. Before using such variables, we usually check if they are null or not to avoid errors like NullPointerException. Instead of using long if-else conditions, we can use the Elvis Operator (?:) to make the code much simpler.
Syntax:
val result = expression ?: default_valueIf expression is not null, it returns the value of the expression. If expression is null, it returns the default_value after ?:.
Without Using Elvis Operator
To normally handle null values using an if-else block we do it the following way as shown below.
Example:
fun main() {
var st: String? = null
var st1: String? = "Geeks for Geeks"
var len1: Int = if (st != null) st.length else -1
var len2: Int = if (st1 != null) st1.length else -1
println("Length of st is $len1")
println("Length of st1 is $len2")
}
Output:
Length of st is -1
Length of st1 is 15
Example:
In this example, for "st", since it is null, we return -1 and for "st1", since it is not null, we return its length (15).
Using Elvis Operator
We can do the same thing more easily using the Elvis Operator (?:) as shown below.
Example:
fun main() {
var st: String? = null
var st1: String? = "Geeks for Geeks"
var len1: Int = st?.length ?: -1
var len2: Int = st1?.length ?: -1
println("Length of st is $len1")
println("Length of st1 is $len2")
}
Output:
Length of st is -1
Length of st1 is 15
Explanation:
- st?.length tries to get the length of "st".
- But since "st" is null, the Elvis Operator (?:) gives the value -1.
- For "st1", which is not null, we get the actual length.