Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Kotlin Elvis Operator(?:)

  • Last Updated : 29 Nov, 2019

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
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!