val x: String? = "foo"
val y: String = x ?: "bar" // "foo", because x was non-null
val a: String? = null
val b: String = a ?: "bar" // "bar", because a was null
如果 first operand不是无效的,那么它将被返回。如果是 是无效的,则返回 second operand。这可以用来保证表达式不会返回 null 值,因为如果提供的值为 null,则将提供一个非空值。
例如(在科特林) :
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"
}
var myStr:String? = null
//trying to find out length of myStr, but it could be null, so a null check can be put as,
val len = if (myStr != null){
myStr.length
}
else{
-1
}
使用 猫王运算符,上面的代码可以写在一行中
val len = myStr?.length ?: -1 // will return -1 if myStr is null else will return length