Builder Pattern in Kotlin (under a minute)
The builder pattern is a creational design pattern that allows you to build complex objects by specifying their parts in a step-by-step fashion. It’s a bit like building a sandwich: you start with the bread, then add the fillings, and finally you put the other slice of bread on top.
Here’s a fun example of how you might use the builder pattern in Kotlin to create a sandwich:
class Sandwich {
var bread: String = ""
var fillings: MutableList<String> = mutableListOf()
}
class SandwichBuilder {
private val sandwich = Sandwich()
fun setBread(bread: String): SandwichBuilder {
sandwich.bread = bread
return this
}
fun addFilling(filling: String): SandwichBuilder {
sandwich.fillings.add(filling)
return this
}
fun build(): Sandwich {
return sandwich
}
}
fun main() {
val sandwich = SandwichBuilder()
.setBread("whole wheat")
.addFilling("lettuce")
.addFilling("tomato")
.addFilling("avocado")
.build()
println("Sandwich with ${sandwich.bread} bread and ${sandwich.fillings.joinToString(", ")} fillings.")
}
This would print out the following: “Sandwich with whole wheat bread and lettuce, tomato, avocado fillings.”
The advantage of using the builder pattern is that it allows you to create complex objects in a more readable and expressive way, without having to use lots of constructors or setter methods. It also makes it easier to add new features to the object being built, because you can simply add new methods to the builder class.