Builder Pattern in Kotlin (under a minute)

Alex Manhooei
1 min readDec 28, 2022

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alex Manhooei
Alex Manhooei

Written by Alex Manhooei

Staff Software Engineer @ Google. All of my blog posts are my personal opinions and not related to my work at google in any shape or form.

No responses yet

Write a response