skip to content
blog.metters.dev

TIL about Kotlin builder functions

/ 2 min read

Some while ago, I wanted to fill a read-only set, over the course of several steps. Originally I would use a mutable set and then convert that object to the immutable pendant. This is a lousy compromise.

We want an immutable set, but it cannot be filled it within a single step. Consequently, we use a mutable set first, which later is converted. Let’s look at an example—Admittedly, the scenario is highly contrived, but bear with me:

getSomeImmutableSet(someProperty: String, anotherProperty: String) : Set {
val mutableSet = mutableSetOf(repository.findByProp(someProperty))
val setOfOtherObjects = mutableSetOf(anotherRepository.findByProp(anotherProperty))
val someOtherSet = setOfOtherObjects.map {it.theActuallyObject}.filter(it.someProperty)
mutableSet.addAll(someOtherSet)
return setOf(mutableSet)
}

Maybe apply{ ... } makes this more concise. We create a mutable collection, fill it with values and immediately convert it to an immutable collection:

getSomeImmutableSet(someProperty: String, anotherProperty: String) : Set {
return mutableSetOf().apply {
addAll(repository.findByProp(someProperty))
val setOfOtherObjects = mutableSetOf(anotherRepository.findByProp(anotherProperty))
addAll(setOfOtherObjects.map {it.theActuallyObject}.filter(it.someProperty))
}.toSet()
}

As I have learnt recently, filling an immutable collection stepwise can be simplified with the help of collection builder functions. The code becomes much simpler in comparison to the first attempt, like so:

getSomeImmutableSet(someProperty: String, anotherProperty: String) : Set {
return buildSet {
addAll(repository.findByProp(someProperty))
val setOfOtherObjects = mutableSetOf(anotherRepository.findByProp(anotherProperty))
addAll(setOfOtherObjects.map {it.theActuallyObject}.filter(it.someProperty))
}
}

buildSet is just syntactic sugar for what is happening in the second code snippet. It solves a quite common problem, that developers face when working with immutable collections. Makes me nearly looking forward to the next time I am facing this issue.

Resources