For classes that contain only data, Kotlin provides an implementation of
- equals
- getHashCode
- toString
- copy
Consider the following examples
class Person (name : String)
Person a = Person ("Tom")
Person b = Person ("Tom")
println(a == b)
this print false because equals compares the objects references.
If instead we use a data class:
data class Person (name : String)
Person a = Person ("Tom")
Person b = Person ("Tom")
println(a == b)
this print true because equals is called on each member, and in this case the two instances have the same name.
It is possible to copy an instance of a data class changing some of its properties:
class Person (name : String, age : Int)
Person a = Person ("Tom", 23)
Person b = a.copy(age = 35)