run scope function in Kotlin

Level 4162 keystrokes

run executes a block and returns its last expression. Called alone, it groups temporary variables; called on an object ("Hello".run), the object is this, so its members such as length can be used directly.

Kotlin code

// run without a receiver: a block whose last expression is the result
1val result = run {
// a and b exist only inside this block
2 val a = 10
3 val b = 20
// 10 + 20 = 30 becomes result
4 a + b
5}
6
// run on a String: inside the block, this is "Hello"
7val length = "Hello".run {
// Runs first, so it prints String: Hello before the other lines
8 println("String: $this")
// this.length of "Hello", 5, is the block's result
9 length
10}
11
// Print Sum: 30
12println("Sum: $result")
// Print Length: 5
13println("Length: $length")

Output

String: Hello
Sum: 30
Length: 5
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.

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

More Kotlin examples at level 4

← Kotlin typing practice