What does "?:" do in Kotlin? (Elvis Operator)

Kotlin Mobile DevelopmentApps/Applications

Elvis operator is very common in many programming languages. This is a binary expression that returns the first operand when the expression value is True and it returns the second operand when the expression value is False. Generally, the Elvis operator is denoted using "?:", the syntax looks like −

First operand ?: Second operand

Example

The following example demonstrates how you can use the Elvis operator in Kotlin.

fun main(args: Array<String>) {
   val x: String? = null
   val y: String = x ?: "TutorialsPoint.com"
   // it will check whether the value of x
   // is NULL or not. If NULL, then
   // it will return y, otherwise x
   println(x ?: y)
}

Output

In the above example, the Elvis operator will check whether the value of "x" is NULL. If yes, then it will return the first operand "x", otherwise it will return "y". As per our example, it will return "y", as the value of "x" is NULL.

TutorialsPoint.com
raja
Updated on 23-Nov-2021 07:16:42

Advertisements