Skip to content
DeveloperMemos

Taking a Look at Kotlin's Elvis Operator

Kotlin, Elvis Operator1 min read

If you have ever written code in Kotlin, you are probably familiar with the concept of null safety. Kotlin's type system is designed to help prevent null pointer exceptions, which can cause crashes and unpredictable behavior in your application. One of the tools that Kotlin provides to help with null safety is the Elvis operator.

The Elvis operator ?: is a shorthand way of checking if a value is null, and providing a default value if it is. The syntax for using the Elvis operator is as follows:

1val result = nullableValue ?: defaultValue

In this example, nullableValue is the nullable variable that we want to check, and defaultValue is the value that we want to use if nullableValue is null. If nullableValue is not null, then result will be set to its value. If nullableValue is null, then result will be set to defaultValue.

Here's an example of how the Elvis operator can be used in Android development:

1val textView: TextView? = findViewById(R.id.text_view)
2val text: String = textView?.text ?: "Default Text"

In this example, we are trying to get the text from a TextView. The findViewById() method returns a nullable TextView, so we use the safe call operator ?. to access its text property. If the TextView is null, then text will be set to "Default Text".

The Elvis operator can also be used with functions that return nullable values. For example:

1val result: String = nullableString() ?: "Default Value"

In this example, nullableString() is a function that returns a nullable String. If the function returns null, then result will be set to "Default Value".

Overall, the Elvis operator is a useful tool for simplifying null safety checks in your Kotlin code. By using the Elvis operator, you can write cleaner and more concise code, while still ensuring that your application is safe from null pointer exceptions.