We often create classes to hold some data in it. In such classes, some standard functions are often derivable from the data. In Kotlin, this type of class is known as data class and is marked as data.
Example of a data :
data class Student(val name: String, val roll_no: Int)
The compiler automatically derives the following functions :
Rules to create Data classes –
Data classes have to fulfill the following requirements to ensure the consistency:
- The primary constructor needs to have at least one parameter.
- All primary constructor parameters need to be marked as val or var.
- Data classes cannot be abstract, open, sealed or inner.
- Data classes may only implement interfaces.
This function returns a string of all the parameters defined in the data class .
man(roll=1, name=man, height=50)
The compiler only uses the properties defined inside the primary constructor for the automatically generated functions.
It excludes the properties that are declared in the class body.
Here height is not used by the toString() function .
Sometimes we need to copy an object, with some change in some of its properties keeping all others unchanged.
In this case copy() function is used.
Properties of copy()
- It copies all arguments or members defined in primary constructor
- Two objects can have same primary parameter values and different class body values if defined
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) .
man(name=manish, age=18) has 100 cm height man(name=rahul, age=18) has 90 cm height man(name=manish, age=18) has 110 cm height
hashCode() and equals()
- hashCode() function returns a hash code value for the object.
- equals() method return true if two objects have same contents and it works similar to “==”, but works different for Float and Double values.
Declaration of hashCode() :
open fun hashCode(): Int
Properties of hashCode()
- Two hash codes declared two times on same object will be equal.
- If two objects are equal according to equals() method, then the hash codes
returned will also be same
835510190 -938448478 835510190 hash1 == hash 2 false hash2 == hash 3 false hash1 == hash 3 true
man1 and man2 have same object contents, so they are equal, thus they have same hash code values.