Data classes are great in Kotlin. I consider it one of the killer features of the language.
They are great to group a few values together, quickly and safely. But what if you want to group a lot of values? With the data class constructor you can only create (immutable) instances when you provide all the values of the data class.
The builder pattern provides a solution for this problem. But what is the most concise and easy way to write this in Kotlin?
Builder inner class
The immutable class is the outer class. The builder is the inner class that is mutable and can be passed around while building the object. This is a very Java-like approach and quite verbose, but still works.
Note that we are using a private constructor so the only way to instantiate a
CombinedData object is using the builder.
Using data classes
In this approach we are using data classes for the builder and the outer (immutable) class. We get all the benefits of the Kotlin data classes (such as automatic
Someone might be able to instantiate a
CombinedData object without using the builder, but if this is not a big deal in your use-case, then this approach is more concise.
Not exactly a builder pattern, but the most quick and dirty way to accomplish a builder-like behavior for a data class is use
copy(). This will require having nullable fields, setting the required fields in each step and resetting the var holding the immutable value. Nevertheless, you won't have to write any additional line of code.