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 greeting1val greeting = run { // name and version are visible only inside this block2 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 block7val length = "Hello World".run { // Runs immediately, so String: Hello World is the first line of output8 println("String: $this") // 11 characters, including the space, becomes length9 this.length10}11 // Print Welcome to Kotlin 1.9!12println(greeting)// Print Length: 1113println("Length: $length")Output
String: Hello World Welcome to Kotlin 1.9! Length: 11
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