📅  最后修改于: 2021-01-05 07:38:49             🧑  作者: Mango
Elvis运算符(?:)用于返回非null值,即使条件表达式为null。它还用于检查值的空安全性。
在某些情况下,我们可以声明一个可以包含空引用的变量。假设一个包含空引用的变量str ,在程序中使用str之前,我们将检查它的可空性。如果发现变量str不为null,则其属性将使用,否则将使用其他一些非null值。
var str: String? = null
var str2: String? = "May be declare nullable string"
在上面的代码中,字符串str包含一个空值,在访问str的值之前,我们需要执行安全检查,无论字符串是否包含value。在常规方法中,我们使用if … else语句执行此安全检查。
var len1: Int = if (str != null) str.length else -1
var len2: Int = if (str2 != null) str.length else -1
fun main(args: Array){
var str: String? = null
var str2: String? = "May be declare nullable string"
var len1: Int = if (str != null) str.length else -1
var len2: Int = if (str2 != null) str2.length else -1
println("Length of str is ${len1}")
println("Length of str2 is ${len2}")
}
输出:
Length of str is -1
Length of str2 is 30
Kotlin提供了称为Elvis运算符(?:)的高级运算符符,即使条件表达式为null,该运算符也会返回非null值。以上如果。 。 。 else运算符可以使用Elvis运算符表示如下:
var len1: Int = str?.length ?: -1
var len2: Int = str2?.length ?: -1
Elvis运算符将表达式左移为?:即-1。 (str ?. length)如果不为null,则返回对(?:) ie(-1)的表达式权限。仅当左侧返回null时,才评估Elvis运算符的右侧表达式。
fun main(args: Array){
var str: String? = null
var str2: String? = "May be declare nullable string"
var len1: Int = str ?.length ?: -1
var len2: Int = str2 ?.length ?: -1
println("Length of str is ${len1}")
println("Length of str2 is ${len2}")
}
输出:
Length of str is -1
Length of str2 is 30
当Kotlin抛出并返回表达式时,它们也可以在Elvis运算符的右侧使用。这可以用于检查功能参数:
funfunctionName(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
fun main(args: Array){
val fruitName: String = fruits()
println(fruitName)
}
fun fruits(): String{
val str: String? ="abc"
val strLength: Int = if(str!= null) str.length else -1
val strLength2: Int = str?.length ?: -1
var string = "str = $str\n"+
"strLength = $strLength\n"+
"strLength2 = $strLength2\n\n"
fun check(textOne: String?, textTwo: String?): String?{
val textOne = textOne ?: return null
val textTwo = textTwo ?: IllegalArgumentException("text exception")
return "\ntextOne = $textOne\n"+
"textTwo = $textTwo\n"
}
string += "check(null,\"mango\") = ${check(null,"mango")}\n" +
"check(\"apple\",\"orange\") = ${check("apple","orange")}\n"
return string
}
输出:
str = abc
strLength = 3
strLength2 = 3
check(null,"mango") = null
check("apple","orange") =
textOne = apple
textTwo = orange