Kotlin Elvis Operator(?:)

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Length of st is -1
Length of st1 is 15
filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Length of st is -1
Length of st1 is 15
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.