Elvis Operator 由一个问号后跟一个冒号表示:?:,它可以与以下语法一起使用:
first operand ?: second operand
它使您可以编写简洁的代码,并且可以这样工作:
如果first operand 不为空,则返回。如果为空,则返回second operand。这可用于保证表达式不会返回 null 值,因为如果提供的值为 null,您将提供一个不可为 null 的值。
例如(在 Kotlin 中):
fun retrieveString(): String { //Notice that this type isn't nullable
val nullableVariable: String? = getPotentialNull() //This variable may be null
return nullableVariable ?: "Secondary Not-Null String"
}
这种情况下,如果getPotentialNull的计算值不为null,则由retrieveString返回;如果为null,则返回第二个表达式"Secondary Not-Null String"。
另请注意,如果左侧为 null,则仅评估右侧表达式。
在 Kotlin 中,您可以使用任何表达式作为 second operand,例如 throw Exception 表达式
return nullVariable ?: throw IllegalResponseException("My inner function returned null! Oh no!")
Elvis Operator 这个名字来源于美国著名歌手Elvis Presley。他的发型像一个问号
资料来源:Wojda、I. Moskala、M. 使用 Kotlin 进行 Android 开发。 2017. Packt 出版