![]() |
VOOZH | about |
In Kotlin, we often create classes just to hold data. These are called data classes, and they are marked with the data keyword. Kotlin automatically creates some useful functions for these classes, so you don’t have to write them yourself.
A data class is a class that holds data. Kotlin automatically provides useful methods like:
Example:
data class Student(val name: String, val rollNo: Int)When you create this class, Kotlin automatically gives it the above functions using the primary constructor parameters (name and rollNo in this case).
To make sure data classes work correctly, Kotlin has some rules:
The toString() function gives you a string showing all the values in the primary constructor.
Example:
Output:
Person(name=man, roll=1, height=50)Note: But if you define properties inside the class body (not in the constructor), toString() won’t include them.
Example:
Output:
Person(name=manish)
70
Here height is not used by the toString() function .
Sometimes, you want to make a copy of an object, but change just one or two values. That’s where the copy() function is useful.
Properties of copy()
Declaration of copy()
fun copy(name: String = this.x, age: Int = this.y) = user(x, y)where user is a data class : user(String, Int) .
Example
Output:
manish, 18 has 100 cm height
rahul, 18 has 90 cm height
manish, 18 has 110 cm height
So, even though the primary constructor values are copied, the values in the class body like height can be changed separately.
Declaration of hashCode() :
open fun hashCode(): Int
Properties of hashCode()
Output:
835510190
-938448478
835510190
man1 == man2: false
man1 == man3: true
Explanation:
man1 and man2 have same object contents, so they are equal, thus they have same hash code values.