Sitemap

Member-only story

Crabby Kotlin: The Kolin-y-est Constructor

2 min readMay 31, 2024

Disclaimer: All opinions are my own

Photo by Tatiana Syrikova from Pexels

Spoiler: I’m not actually creating any kind of new constructor.

Rather, this is a very, very Kotlin-y pattern (in my opinion) for creating new objects that I’ve seen recently.

Let’s say you’ve got a class like

data class MyClass(val myName: String?)

This is a trivial example, but pretend that it’s much longer with lots of optional parameters. You could use some of the Kotlin options that exist already like named parameters, but what if you wanted another option? You might consider a builder.

Builders are fun, and have been around for a long time. They don’t really require any unique language features. You might add a builder like this

class MyClassBuilder {
var myName: String? = null
fun build() = MyClass(myName)
}

Makes sense so far. But what if you wanted…a more Kotliny way to use the builder?

You might add a function that takes a block and applies it to a newly created object.

“Huh?” I hear you say.

public inline fun myClass(block: MyClassBuilder.() -> Unit): MyClass {
val myClass = MyClassBuilder()
myClass.block()
return myClass.build()
}

--

--

Brian Olson
Brian Olson

Written by Brian Olson

Engineer, formerly at Amazon, currently at Google. All opinions are my own. Consider supporting here: https://devblabs.medium.com/membership

No responses yet