Null Coalescing Elvis Operator
suggest changeSometimes 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
NullPointerExceptioncan be thrown with the assertion operator (for example,data!!.second()).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents