The Elvis operator

The Elvis operator is a terse structure that is present in Kotlin. It takes the following form:

(expression) ?: value2

Its usage in a Kotlin program is demonstrated in the following code block:

val nullName: String? = nullval firstName = nullName ?: "John"

If the value held by nullName is not null, the Elvis operator returns it, otherwise the "John" string is returned. Thus, firstName is assigned the value returned by the Elvis operator.

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.