CodeBlanks Logo Icon CodeBlanks

Elvis operator

Learn the Elvis operator with ?: and null safety.

The Elvis operator

The Elvis operator ?: returns the value itself when it is not null, otherwise a default value. Its name comes from the ?: sign resembling a smiley (Elvis Presley).

In val name = input ?: "Guest", if input is null, name becomes "Guest"; otherwise it becomes input itself.

val input: String? = null
val name = input ?: "Guest"
println(name)  // Guest

Practice Try Elvis

At the top level, declare val input: String? = null. Inside fun main(), declare val name = input ?: "Guest" and print with println(name).

Sample solution

Main.kt
val input: String? = null

fun main() {
    val name = input ?: "Guest"
    println(name)
}

Expected output

Guest

Null safety

In Kotlin a type cannot be null by default; String cannot be null but String? can. The Elvis operator ?: handles nullable values safely.

There is also the !! operator; but it throws NullPointerException if the value is null. Elvis is safer; it gives a default value and prevents the program from crashing.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Elvis operator: fill in the missing part

Question
val name = input ____ "Guest"
Answer
val name = input ?: "Guest"

Explanation: With ?: you give a default for the null case.

2 When is the Elvis operator used?

  • In class definitions
  • Only for arithmetic
  • In loops
  • To give defaults to null values Correct answer

Explanation: ?: gives a default in null cases.

3 Elvis operator: match the terms

Term Meaning
?: Elvis
&& And
|| Or
! Not

All lessons in Beginner