Kotlin Elvis運算符

Elvis運算符(?:)用於返回非null值,即使條件表達式爲null。 它還用於檢查值的空安全性。

在某些情況下,可以聲明一個保存空引用的變量。 假設一個包含空引用的變量str,在程序中使用str之前將檢查它的可空性。 如果發現變量str不爲null,則其屬性將使用,否則使用其他非空值。

var str: String? = null   
var str2: String? = "May be declare nullable string"

在上面的代碼中,str包含一個null值,在訪問str的值之前需要執行安全檢查,字符串是否包含值。 在傳統方法中,使用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<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

當Kotlin拋出並返回一個表達式時,它們也可以在Elvis運算符的右側使用。 這可以用於檢查函數參數:

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