• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - How to implement Builder pattern in Kotlin?

Answer -

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()

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners