3 ms·
Builders can set multiple fields of the data class at once, e.g. from a single builder parameter. They also can perform error checking whether the thing that th
by Matthias247 9y ago
Builders can set multiple fields of the data class at once, e.g. from a single builder parameter. They also can perform error checking whether the thing that the user actually wanted to build is consistent before returning a data class. There might be multiple fields in a class where the value of one field restricts possible values of another one.
These are already some reasons why you want users to create objects through builders instead of initializing them directly.
Another thing that builders provide is interface isolation: If your data class is only interpreted by your own libraries code you can modify it's (package-private) content as you like and require. The builder can evolve (and fill in additional fields as needed), and your code which consumes the built data class can evolve without breaking a user contract. Just the builder API needs to be stable (or backward compatible).
With data classes this wouldn't work that easy, since you require the user to specify more parameters directly.