Demystifying Kotlin Data classes

Shivam
2 min readJan 11, 2020

--

Photo by bruce mars on Unsplash

Hello,

In this series of posts on data classes, I will try to cover most of the things related to data classes right from the basic introduction to how it works. I have divided this series into 3 smaller parts.

In part-I:

  • We will cover what is data class and how it will help us to reduce the boilerplate code.
  • We will also discuss what are the requirements of a class to be a data class.
  • We will see the methods that the data class generates for us.
  • Should we use Val or Var with the parameters of the data class in the constructor?

In part-II:

In part II we will cover the following things:

  • What are the componentN() and copy() methods in detail.
  • We will also learn about the rules that Kotlin compiler uses to generate these methods.

In part-III:

This part mostly contains tips about the data classes like:

  • Why we should avoid declaring variables inside the `class body` of the data class.
  • what is Destructuring Declaration and how we can use it?
  • Why should we declare a constructor parameter as val instead of var?
  • How can use Kotlin’s @Parcelize annotation for Parcelable and reduce the boilerplate code?

Further Reading:

Thanks, Happy Coding 👏.

--

--

Shivam

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