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
Create a free account and build your private vault. Share publicly whenever you want.