# Kotlin Elvis運算子

`Elvis`運算子(`?:`)用於返回非`null`值，即使條件表示式為`null`。 它還用於檢查值的空安全性。

``````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) str.length else -1
``````

``````fun main(args: Array<String>){

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運算子(`?:`)的高階運算子，即使條件表示式為空，也返回非空值。 以上`if...else`運算子可以使用Elvis運算子表示如下：

``````var len1:  Int = str?.length ?: -1
var len2:  Int = str2?.length ?:  -1
``````

Elvis運算子將表示式返回`?: -1`。 (`str ?.length`)如果它不為`null`，否則它將表示式返回`?:`， 即`-1`。 僅當左側返回`null`時，才會評估Elvis運算子的右側表示式。

Kotlin Elvis運算子範例

``````fun main(args: Array<String>){

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
``````

``````funfunctionName(node: Node): String? {
val parent = node.getParent() ?: return null
val name = node.getName() ?: throw IllegalArgumentException("name expected")
// ...
}
``````

Kotlin Elvis運算子使用throw和return表示式

``````fun main(args: Array<String>){
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
``````