Computing values with run in Kotlin

Level 5210 keystrokes

run executes a block and returns its last expression. Without a receiver it keeps helper variables local to the block; on an object ("Hello World".run) the object becomes this. Note the order of the output: the second block prints while it runs, before the final println calls.

Kotlin code

// run without a receiver: the block's last expression becomes greeting
1val greeting = run {
// name and version are visible only inside this block
2 val name = "Kotlin"
3 val version = "1.9"
// The result: "Welcome to Kotlin 1.9!"
4 "Welcome to $name $version!"
5}
6
// run on a String: this is "Hello World" inside the block
7val length = "Hello World".run {
// Runs immediately, so String: Hello World is the first line of output
8 println("String: $this")
// 11 characters, including the space, becomes length
9 this.length
10}
11
// Print Welcome to Kotlin 1.9!
12println(greeting)
// Print Length: 11
13println("Length: $length")

Output

String: Hello World
Welcome to Kotlin 1.9!
Length: 11
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.

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

More Kotlin examples at level 5

← Kotlin typing practice