How to implement Builder pattern in Kotlin?

Technology CommunityCategory: KotlinHow to implement Builder pattern in Kotlin?
VietMX Staff asked 11 months ago

First and foremost, in most cases you don’t need to use builders in Kotlin because we have default and named arguments but if you need one use:

class Car( //add private constructor if necessary
        val model: String?,
        val year: Int
) {

    private constructor(builder: Builder) : this(builder.model, builder.year)

    class Builder {
        var model: String? = null
            private set

        var year: Int = 0
            private set

        fun model(model: String) = apply { this.model = model }

        fun year(year: Int) = apply { this.year = year }

        fun build() = Car(this)
    }
}

Usage:

val car = Car.Builder().model("X").build()