Core Builder Functions

  • buildList {} - Creates immutable List
  • buildSet {} - Creates immutable Set (preserves insertion order)
  • buildMap {} - Creates immutable Map
  • buildString {} - Creates String using StringBuilder

Primitive Specializations (Avoid Boxing)

  • List: buildIntList{}, buildLongList{}, buildFloatList{}, buildDoubleList{}
  • Set: buildIntSet{}, buildLongSet{}, buildFloatSet{}
  • Map: buildIntIntMap{}, buildObjectFloatMap{}, etc.

Key Benefits

  • Write cleaner code with conditionals
  • Skip conversion from mutable to immutable
  • Inline functions (no lambda overhead)
  • Standardize collection creation

Practical Examples

Complex Conditional Logic

val config = buildMap {
    put("env", "dev")
    
    if (debug) {
        put("logLevel", "DEBUG")
        put("metrics", "enabled")
    }
    
    if (auth) put("auth", "OAuth2")
}

Nested Structures

val users = buildList {
    add(User("Alice", buildList {
        add("admin")
        if (hasKotlinAccess) add("kotlin")
    }))
    
    if (includeGuest) {
        add(User("Guest", buildList { add("readonly") }))
    }
}

Implementation Details

  • Builder functions use mutable collections internally
  • Return immutable collections when done
  • All are inline functions (code copied to call site)
  • Thread-safe after creation (immutable result)

Custom Builders

// Define your own builder function
inline fun buildPerson(
    name: String, 
    block: MutableList<String>.() -> Unit
): Person {
    return Person(name, buildList(block))
}
 
// Use it
val person = buildPerson("Alice") {
    add("friendly")
    if (isSmart) add("smart")
}

Usage Notes

  • Introduced in: String builder (1.1), others (1.6)
  • Best for conditional collection building
  • Makes code intention clearer
  • Produces immutable collections
  • Work well with other Kotlin DSL features

Compared to Traditional Approach

// Before:
val list = mutableListOf<String>()
list.add("item1")
if (condition) list.add("item2")
val immutableList = list.toList()
 
// After:
val list = buildList {
    add("item1")
    if (condition) add("item2")
}