Elvis Operator in Kotlin

Level 271 keystrokes

Uses the Elvis operator ?: to provide a default value when a variable is null.

Kotlin code

// A nullable String that currently holds null
1val name: String? = null
// ?: returns the left side if it is not null, otherwise the right side
// name is null, so result becomes "Unknown"
2val result = name ?: "Unknown"
// Prints Unknown
3println(result)

Output

Unknown
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • :× 2
  • ?× 2
  • "× 2
  • =× 2
  • (× 1
  • )× 1

More Kotlin examples at level 2

← Kotlin typing practice