Building a value with with in Kotlin
Level 5203 keystrokes
with(obj) { } runs a block with obj as this, so text can be used without repeating the object, and returns the last expression. The block appends four pieces to text and returns the finished "Hello World!" (12 characters).
Kotlin code
// A small data class with a mutable text property, empty by default1data class StringBuilder2(var text: String = "")2 // Inside with, this is the new StringBuilder2 object3val result = with(StringBuilder2()) { // text += creates a new String each time and assigns it to this.text4 text += "Hello"5 text += " "6 text += "World"7 text += "!" // The last expression is the result: "Hello World!"8 text9}10 // Print Hello World!11println(result)// 12 characters including the space and !: prints Length: 1212println("Length: ${result.length}")Output
Hello World! Length: 12
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=× 6(× 5)× 5+× 4:× 2{× 2}× 2!× 1.× 1