Kotlin Programming By Example
上QQ阅读APP看书,第一时间看更新

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? = null
val 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.