How to use the Data class in Kotlin
Overview
Data classes in Kotlin are similar to POJO classes in Java. The main purpose of Data classes is to hold data. These classes contain some standard functionality and utility functions that can be mechanically derived from the data. ‘Data’ classes are simple to use and can help us avoid lots of boilerplate code.
Syntax
data class Person(val name:String, val age:Int, val isMarried:Boolean)
The code above is an example of a Data class instance. The data keyword differentiates normal classes from data classes.
Additional functions
The Data class comes with a handful of other functions:
-
equals(): Returnstruewhen two objects have the same content. -
hashCode(): Returns the hashcode value of the object. -
copy(): We can use this function to copy an object and modify its value. -
toString(): Returns an object as a readable string.
The copy method
We can use the copy method to copy an object and modify its value. Let’s look at an example:
val x = Person("Zara", 25, false)
val y = x.copy(isMarried = true)
In the example above, we copy the data from variable x into variable y. While copying the data, we also modify the data from variable x and add new data (isMarried).
Destructuring declarations
val x = Person("Zara", 25, false)
val (name,age,isMarried) = x
The code above is an example of multi-declaration; each property is mapped into an object, so the functions provide direct access to the data that is in the data model class.
The Person data class is stored by the variable (name,age,isMarried). These variables are all stored as an object, and in the next line, the data is directly assigned to variables.
Component
val name = x.component1() // Zara
val age = x.component2() // 25
val isMarried = x.component3() // false
The componentX functions are created automatically and help us simplify the code.
Note:
- The primary constructor of the
Dataclass should create at least one variable.- The primary variable should be indicated as
varorval.