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—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:
Maybe apply{ ... }
makes this more concise. We create a mutable collection, fill it with values and immediately convert it to an immutable collection:
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:
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
- Official documentation
- KotlinDoc of builder function for sets