Open In App

Kotlin Elvis Operator(?:)

Improve
Improve
Like Article
Like
Save
Share
Report

Elvis Operator (?:)It 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. If a variable st which contains null reference, before using st in program we will check its nullability. If variable st found as not null then its property will use otherwise use some other non-null value.




// Kotlin Program without using Elvis Operator
fun main(args: Array<String>)
{  
var st: String? = null 
var st1: String? = "Geeks for Geeks" 
var len1:  Int = if (st != null) st.length else -1 
var len2:  Int = if (st1 != null) st1.length else -1 
println("Length of st is ${len1}")  
println("Length of st1 is ${len2}")  
}  


Output:

Length of st is -1
Length of st1 is 15




// Kotlin Program using Elvis Operator
fun main(args: Array<String>)
{    
var st: String? = null 
var st1: String? = "Geeks for Geeks" 
var len1:  Int = st ?.length ?: -1 
var len2:  Int = st1 ?.length ?:  -1 
     
println("Length of st is ${len1}")  
println("Length of st1 is ${len2}")  


Output:

Length of st is -1
Length of st1 is 15

Last Updated : 29 Nov, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads