Null Coalescing Elvis Operator

suggest change

Sometimes it is desirable to evaluate a nullable expression in an if-else fashion. The elvis operator, ?:, can be used in Kotlin for such a situation.

For instance:

val value: String = data?.first() ?: "Nothing here."

The expression above returns "Nothing here." if data?.first() or data itself is null. Otherwise it returns the result of data?.first().

It is also possible to throw exceptions using the same syntax to abort code execution.

val value: String = data?.second() 
    ?: throw IllegalArgumentException("Value can't be null!")

Reminder: a NullPointerException can be thrown with the assertion operator (for example, data!!.second()).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents