What do data classes give you in Kotlin?
Data classes are a well-known feature in Kotlin. They’re appropriately named, since it’s designed for classes that hold data—that’s where the main value of this feature come into play.
When you mark a class with the data
keyword, the benefits are as follows.
toString()
The first and most dominant benefit is that data classes define a toString()
function for you. If it was just this, I’d be happy already. Its so simple, but everytime I use a data class I appreciate it.
Here’s the the toString
function in action:
equals()
and hashcode()
A second, nice benefit we get when using data classes is an equals()
and a hashCode()
method.
This equals()
refers to structural equality, meaning if two objects have all the same properties, count them as equal. They don’t have to sit at the same place in memory, i.e. literally be the same object. To use referential equality (memory location), use ===
.
If two objects are structurally equal, the value returned by their two corresponding hash code functions will be the same.
Destructurability (componentN()
Functions)
Oftentimes you’ll want to destructure values from an object. We can easily use destructuring with an object whose type is a data class:
Can we do this with a normal class?
When we destructure, it gets compiled to something called componentN()
functions. They have to be present on the object for the object to be destructurable. Data classes put them there.
How many of these are generated? The compiler only uses the properties included in the primary constructor, when you define the class. So in this case, there’s just 2.
Note that if you use an underscore, the componentN()
function doesn’t even get called.
Copy
Another benefit is data classes automatically define a copy method, allowing us to copy some or all of the properties.
This is useful if you want to write a pure function, and you’re returning an output that’s only a slightly altered version of the endpoint.
Without the data
keyword
Just to finalize our understanding, let’s look at all the stuff we’d have to do if the data
keyword didn’t exist.
When should you not use data classes?
Whenever some feature seems too good to be true, like database indexes or exactly once processing in Kafka, remember nothing comes for free.
Here’s an interesting article measuring the cost of the data class, but I would still strongly advocate for making all model / entity / schema classes data classes.
Summary
One of the goals of the Kotlin language designers was to have a concise but understandable language. Clearly, one of the chief complaints about Java is that it is verbose. With data
classes, Kotlin eliminates a ton of unnecessary code, in a simple and easy to use way.
Sources
Wow! You read the whole thing. People who make it this far sometimes
want to receive emails when I post something new.
I also have an RSS feed.