We’ve already seen the classes in an earlier article, but data classes go a little further in helping us simplify our code.

What are data classes?

A data class is a class that only contains state and does not perform any operation.

The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.

In particular, it gives us all this for free:

  • The properties declared in the constructor: this technically is not exclusive to a data class, but it avoids all the boilerplate of getters and setters, in addition to the constructor.
  • equals() / hashCode()
  • A set of functions called componentX(), which allow us to do a cool thing we’ll see later.
  • copy()method, very useful when we use immutable objects.

¿How is Java code compared to a data class?

Here comes the awesomeness. Although almost all this code is generated by the IDE, in Java we need this to implement a data class:

And we would still be far from achieving the same amount of functionality that Kotlin provides with this line:

This is where we really see Kotlin’s potential, in the amount of useless code that saves us.

Classes destructuring

That’s the use of componentX functions. Thanks to them, you can decompose a data class in variables this way:

Thanks to this, you can do things like decomposing map pairs inside a loop:

Objects copy

As we’ve talked before, it’s a good practice to us immutability in every possible situations. If we implement previous class as immutable:

If we now want to change the surname, we won’t be able.

When you work with immutability, to change the state of an object you need to copy it with the new value. And that’s the use of copy function:

The copy function can receive as many parameters as values you need to change. As you can see, function parameters can be named, so you can specify which ones you want to modify.

Conclusion

data classes saves a lot of boilerplate that Java forces us to generate, so you end up with a code that is easier to understand and to maintain.

If you liked this article, you can continue learning Kotlin by getting my free guide, where I show you how to create your first Kotlin project from scratch.

Author: Antonio Leiva

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares
%d bloggers like this: