let with the Elvis operator in Kotlin

Level 4122 keystrokes

?.let runs its block only when name is not null and returns the block's last expression. If name were null, the whole ?.let would be null and the Elvis operator ?: would supply 0 instead.

Kotlin code

// A nullable String holding "Kotlin"
1val name: String? = "Kotlin"
2
// The block runs only if name is not null; it is the non-null String
3val length = name?.let {
// Print Name is Kotlin
4 println("Name is $it")
// The last expression is the block's result: 6
5 it.length
// ?: gives 0 if the left side is null, so length is an Int, never null
6} ?: 0
7
// Print Length: 6
8println("Length: $length")

Output

Name is Kotlin
Length: 6
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.

  • "× 6
  • :× 3
  • ?× 3
  • .× 2
  • (× 2
  • )× 2
  • =× 2
  • $× 2
  • {× 1
  • }× 1

More Kotlin examples at level 4

← Kotlin typing practice