Elvis Operator (?:) in Kotlin

Definition

  • This operator is used for null safety in Kotlin.
  • It is mainly used for operations involving boxed values (Values which may hold "null").
  • It is represented by "?:" 
  • If the value to the left of Elvis Operator is null, the value on the right side of the operator is returned as the result.
  • If the value to the left sidde of Elvis Operator is not null then the same value is returned as the result.

Syntax

/*If the value at the variable "string" is null, "100" is assigned to the variable "length" and if it is not null, the value of the length of the string is assigned to the variable "length".*/
value length = string?.length ?: 100

Elvis Operator (?:) Example Program in Kotlin

//Elvis Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
    //Declaring a boxed string and assigning a non-null value
    var name: String? = "Little Drops"

    var result = getLength(name)
    println("Length of $name is $result")
    //Assigning null to the name variable
    name = null

    result = getLength(name)
    println("Length of $name is $result")
}

//Function to find the length of a boxed string which returns 0 when the string is null.
fun getLength(name : String?) : Int?{
    return name?.length ?: 0
}

Sample Output

Length of Little Drops is 12
Length of null is 0