let scope function in Kotlin

Level 3107 keystrokes

?.let runs the block only when the value is not null; inside it the value is it, and the last expression becomes the result. If text were null, result would be null.

Kotlin code

// A nullable String (String?) that currently holds "Hello"
1val text: String? = "Hello"
// ?.let runs the block only if text is not null; inside, it is the non-null String
2val result = text?.let {
// Print Value: Hello
3 println("Value: $it")
// The last expression is the block's result: "HELLO"
4 it.uppercase()
5}
// Print HELLO (it would print null if text were null)
6println(result)

Output

Value: Hello
HELLO
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.

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

More Kotlin examples at level 3

← Kotlin typing practice