Kotlin Null Coalescing / Elvis Operator


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 yield a null value else 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: NullPointerExceptions can be thrown using the assertion operator (e.g. data!!.second()!!)