typestar

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

  1. joinToString takes a separator, plus optional prefix and postfix.
  2. buildString scopes a StringBuilder; appendLine grows it.
  3. List(3) { it * it } sizes a list and computes each slot from its index.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Generics & delegation, step 24 of 27 in Language basics.

← Previous Next →