Junior — Middle
How to implement the Builder pattern in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the Builder pattern can be implemented using a class with an internal DSL or with a nested Builder class. The apply function is often used for convenient object configuration.
Example of a classic Builder with a nested class:
class User private constructor(
val name: String?,
val age: Int?
) {
data class Builder(
var name: String? = null,
var age: Int? = null
) {
fun name(name: String) = apply { this.name = name }
fun age(age: Int) = apply { this.age = age }
fun build() = User(name, age)
}
}
// Usage:
val user = User.Builder()
.name("Ivan")
.age(30)
.build()
You can also use a function with a lambda and apply for a more idiomatic Kotlin style:
data class User(var name: String? = null, var age: Int? = null)
fun user(block: User.() -> Unit) = User().apply(block)
// Usage:
val user = user {
name = "Ivan"
age = 30
}