Builders and joinToString in Kotlin
Format collections without loops, build strings without concatenation.
fun main() {
val stops = listOf("Aspen Gate", "Windy Col", "The Cirque")
// joinToString formats a list without a manual loop.
println(stops.joinToString(" -> "))
println(stops.joinToString(", ", prefix = "[", postfix = "]"))
// buildString grows one StringBuilder behind a clean block.
val board = buildString {
appendLine("TRAIL BOARD")
stops.forEachIndexed { i, s -> appendLine("${i + 1}. $s") }
}
print(board)
println(List(3) { it * it })
}
How it works
joinToStringtakes a separator, plus optionalprefixandpostfix.buildStringscopes aStringBuilder;appendLinegrows it.List(3) { it * it }sizes a list and computes each slot from its index.
Keywords and builtins used here
funitmainval
The run, in numbers
- Lines
- 15
- Characters to type
- 446
- Tokens
- 110
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 102 seconds.
Step 3 of 3 in Generics & delegation, step 24 of 27 in Language basics.