Kotlin Data Class Constructor Problem — Follow Up

Gopal Sharma
Surya Dev Blog
Published in
2 min readAug 18, 2017

--

Source: https://kotlinlang.org/docs/reference/faq.html#where-can-i-get-an-hd-kotlin-logo

I wrote about a problem I was having with Kotlin data class constructors a few days ago. I sent it to a few people and asked for thoughts on how they might address the issue.

A few people proposed a few different possible solutions to the problem. I thought I’d write them down here, as well as what I ended up doing.

Make constructor private

One proposed solution was to make the constructor private and instead have a factory method:

On the face of it, this looks like a good solution. However, there is a problem with it that IDEA very nicely warns you about: the copy method.

Even if you make the constructor private, it is still exposed by the copy method that is generated by the compiler.

You could still write something like this:

which is problematic.

Make fields private

Another proposed solution looks like this:

There’re unfortunately a couple of problems with this as well. First, every time you read name, or emailId you end up creating a whole new object, which means more garbage. This seems unnecessarily wasteful.

Second, the call site becomes ugly:

Admittedly, this is not a problem if you don’t use named parameters. However, named parameters are super useful, especially when you have model objects (the obvious use case for data classes) with > 5 parameters. It significantly reduces the likelihood of making a mistake.

Eventual non solution

Eventually, I wasn’t able to find any solutions to this problem that still allowed me to use data classes. So I ended up not using a data class, and instead writing out all the boilerplate necessary:

Not ideal, but it works…

If you have a better solution in mind, please do let me know: @gopalkri!

Originally published at gopalkri.com on August 18, 2017.

--

--

I do web and iOS stuff for a living. Mega Michigan Football, Bengaluru FC and Arsenal FC fan. Mediocre photographer.