|
Kotlin has a concept called "data classes". Data classes are similar to normal classes, but the compiler automatically generates equals, hashCode, toString, componentN, and copy functions for them.
|
class UserClass(val name: String, val age: Int)
|
|
A data class can be defined similarly to a normal class, but the definition is prefixed with the data keyword.
|
data class UserDataClass(val name: String, val age: Int)
val user1 = UserClass("Henk", 54)
val user2 = UserClass("Henk", 54)
val dataUser1 = UserDataClass("Henk", 54)
val dataUser2 = UserDataClass("Henk", 54)
|
|
By default, classes use referential equality, which means that different instances of the class are never equal, even when all all the properties are.
|
|
|
The equals method (which is called by the equality operator) generated for data classes returns true iff all the properties are equal.
|
println(dataUser1 == dataUser2)
|
|
For data classes, a toString method is generated, so that we can print instances of data classes without needing to manually implement a toString method.
|
|
|
For a data class with two properties, component1 and component2 functions are generated, which allows us to do a "destructuring declaration".
|
val (name, age) = dataUser1
|
|
Data classes also have an autogenerated copy function, which allows you to make a shallow copy, while overwriting some values.
|
val anotherPerson = dataUser1.copy(name="Jaap")
|