Demystifying Kotlin Data classes Part III

Shivam
4 min readJan 11, 2020

--

This is part III of the Demystifying Kotlin Data class series, over the series we will study the in and outs of the Kotlin Data classes.

In the third and last part, I am going to give some tips which I have learned while working with the Data classes, Let’s go through them one by one.

But before going further if you haven’t read Part I and Part II of this series, I would recommend you read them before going further.

# I — Avoid declaring variables inside the `class body` of data class:

As we know the Kotlin compiler only uses the properties defined inside the primary constructor for the automatically generated implementation.

If we want to exclude the properties from the auto-generated methods, then we can declare it inside the class body:

Now only the property `name` will be used inside all the auto-generated methods toString(), equals(), copy(), hashCode() and component1(). And the age property will be ignored in all of these methods. Note — getter/setter will still be created for the age property.

Now let’s consider the following 2 user objects with the same name but different value for age :

If we compare these 2 objects using equals() we get the result as True , means these both objects are the same even though they have different ages. 😕

A solution to the above problem is — Write your own equals() or Don’t declare variables inside the data class body.

# II — Returning multiple values from a function using data class:

Using Destructuring Declaration we can return multiple values from a method. Before going further let’s see what is Destructuring Declaration(DD).

# Destructuring Declaration

  • DD helps to destructure an object into a multiple of variables. It creates multiple variables at once.
  • Component functions generated for data classes enable their use in DD.
  • Above DD declaration compiles down to the following code:

val userName = user.component1()
val userAge = user.component2()

Now we know what destructuring declaration is, let’s come back to our original problem statement of returning multiple values from a function.

Let’s say we are working for some secret agency and we want to return 2 values from our nextMission() method, such as a missionCode and a missionDescription.
A compact way of doing this in the Kotlin is to declare a data class called Missionand return its instance from nextMission(). for example

Let’s declare a method to get Mission details:

Now to use this Mission details:

Since data class automatically declares componentN() functions, DD uses this to de-structure Mission and creates code and description out of it. This down the line becomes

val code = mission.component1()
val description= mission.component2()

# III — Avoid using Pair and Triple:

We could use the standard data classes Pair and Triple, In most cases, though named data classes are better design choice because they make code more readable by providing more meaningful names for properties.

# IV — Use Val over Var

We can declare properties of a data class either as var(mutable) or val (immutable). The only difference between them is — setters will not be created for val properties.

  • It is highly recommended that we should use val this will give us benefits while working with multi-threaded applications.
  • This is also recommended when writing code in a functional programming style where a pure function which takes an instance of data class as input and does some operations on it and returns a new instance of the data class. We can use the copy() function to copy an existing object into a new object and modify some of the properties while keeping the existing object unchanged.

# V — Use Kotlin’s @Parcelize annotation for Parcelable

This is specific to Android application development using Kotlin. In an android most of the time, we need to share an instance data class with other android components like activity or fragment which accepts data of Parcelable type. We can use @Parcelize annotation which generates the boilerplate code for writing an object to and creating an object from `Parcel`.

Here is code for User data class with Parcelable implementation:

It can be simplified to the following code by just using @Parcelize

Thanks. That’s all. I will try to keep this series updating as I discover new things related to data classes in Kotlin. I hope this post helps you to learn more about what is Data class and how to use it.

If you have any suggestions or questions, please add it in the comment below. Thanks again for reading, Happy Coding 👏.

--

--

Shivam

Product Engineer @ Gojek. Likes to write on Productivity, Android App Development, Kotlin, Software Engineering, etc.