Sobes.tech
Junior — Middle

How can the Builder pattern be implemented in Kotlin without using additional classes?

sobes.tech AI

Answer from AI

In Kotlin, you can implement the Builder pattern without creating a separate class by using functions with lambdas and a DSL approach. This allows for creating objects with configurable parameters more compactly and readably.

Example of implementing a Builder using a function and apply:

class User(var name: String = "", var age: Int = 0)

fun user(block: User.() -> Unit): User {
    return User().apply(block)
}

// Usage:
val newUser = user {
    name = "Ivan"
    age = 30
}

Here, the user function creates a User object and applies a configuration block to it, replacing the traditional Builder with multiple set methods.

This approach is convenient for configuring objects with many optional parameters without extra code.