Javatpoint Logo
Javatpoint Logo

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.

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.

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:

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

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:

Kotlin Elvis Operatorusing throw and return expression

Output:

str = abc
strLength = 3
strLength2 = 3

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





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA