9- Data Classes
9- Data Classes
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 :
equals()
hashCode()
toString()
copy()
toString()
This function returns a string of all the parameters defined in the data class .
Example:
val man1=man(1,"man",50)
Output:
Note:
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.
Example:
val man1=man("manish")
//class body properties must be assigned uniquely
man1.height = 70
Output:
man(name=manish)
70
copy()
Declaration of copy()
Output:
Declaration of hashCode() :
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
val hash1=man1.hashCode();
val hash2=man2.hashCode();
val hash3=man3.hashCode();
println(hash1)
println(hash2)
println(hash3)
Output:
835510190
-938448478
835510190
hash1 == hash 2 false