Kotlin

buildString / buildList / buildMap

admin by @admin ADMIN
4h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Stdlib builders that give you a mutable scope, then return an immutable result. Replaces `StringBuilder().apply { ... }.toString()` boilerplate; the result type is the read-only one.
Kotlin
Raw
fun main() {
    // buildString — like StringBuilder, but cleaner
    val sql: String = buildString {
        append("SELECT id, name FROM users\n")
        appendLine("WHERE status = 'active'")
        append("ORDER BY id DESC LIMIT 100")
    }
    println(sql)

    // buildList — start mutable, return List<T>
    val nums: List<Int> = buildList {
        add(1)
        addAll(2..5)
        if (someCondition()) add(99)
    }
    println(nums)

    // buildMap — same idea, returns Map<K, V>
    val config: Map<String, Any> = buildMap {
        put("host", "localhost")
        put("port", 8080)
        if (devMode()) put("debug", true)
    }
    println(config)

    // buildSet — for the rare case you need an immutable Set with conditional content
    val tags: Set<String> = buildSet {
        add("public")
        add("featured")
        if (isPaid()) add("pro")
    }
    println(tags)
}

fun someCondition() = true
fun devMode()       = false
fun isPaid()        = true
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.