Industrial Training




Kotlin Elvis Operator


Elvis operator (?:) is used to return the not null value even the conditional expression is null. It is also used to check the null safety of values. In some cases, we can declare a variable which can hold a null reference. Suppose that a variable str which contains null reference, before using str in program we will check it nullability. If variable str found as not null then its property will use otherwise use some other non-null value.



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

In above code, the String str contains a null value, before accessing the value of str we need to perform safety check, whether string contain value or not. In conventional method we perform this safety check using if ... else statement.


var len1: Int = if (str != null) str.length else -1  
var len2:  Int = if (str2 != null) str.length else -1  
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}")  
}  
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}")  
}  			  

Output:
Length of str is -1
Length of str2 is 30

Kotlin provides advance operator known as Elvis operator(?:) which return the not null value even the conditional expression is null. The above if . . . else operator can be expressed using Elvis operator as bellow:


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

Elvis operator returns expression left to ?: i.e -1. (str?. length) if it is not null otherwise it returns expression right to (?:)i.e(-1). The expression right side of Elvis operator evaluated only if the left side returns null.


Kotlin Elvis Operator example


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}")  
}  
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}")  
}  			  

Output:
Length of str is -1
Length of str2 is 30

As Kotlin throw and return an expression, they can also be used on the right side of the Elvis operator. This can be used for checking functional arguments:


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

Kotlin Elvis Operatorusing throw and return expression


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

Output:
str = abc
strLength = 3
strLength2 = 3

check(null,"mango") = null
check("apple","orange") = 
textOne = apple
textTwo = orange


Hi I am Pluto.