Google News
logo
Kotlin - Interview Questions
What is the Elvis operator in Kotlin?
The Elvis operator (`?:`) is a useful operator in Kotlin that provides a concise way to handle nullability and provide default values when dealing with nullable expressions. It allows you to specify an alternative value to be used when a nullable expression evaluates to null.

The syntax of the Elvis operator is as follows:
expression ?: defaultValue​

Here's how the Elvis operator works :

* If the expression on the left side of the `?:` operator is not null, the value of that expression is returned.
* If the expression on the left side is null, the value of the expression on the right side (the defaultValue) is returned instead.

The Elvis operator is particularly handy when assigning values to variables or providing default values in situations where a nullable expression might result in null. It simplifies the code by handling nullability and providing a fallback value in a single line.

Here's an example that demonstrates the usage of the Elvis operator :
val nullableValue: String? = getNullableValue()
val nonNullValue: String = nullableValue ?: "Default Value"

// Using the Elvis operator in an assignment
val result: Int = computeResult() ?: throw IllegalStateException("Result is null")​
In the above code snippet, `nullableValue` is a nullable String that may or may not be null. The Elvis operator is used to assign the value of `nullableValue` to `nonNullValue`. If `nullableValue` is not null, its value is assigned to `nonNullValue`. Otherwise, the default value `"Default Value"` is assigned.

In the second example, the Elvis operator is used in an assignment where `computeResult()` returns a nullable `Int`. If the result is not null, it is assigned to `result`. However, if the result is null, an `IllegalStateException` is thrown.

The Elvis operator simplifies null handling and allows for concise and expressive code when dealing with nullable values and providing default values or fallback behavior.
Advertisement