Data classes
Data classes are one more concept that Kotlin uses to be a more productive language. To show this, let's go back to our User
class in Java. If we wanted to compare this type by the values it holds (its properties), we would have to override the equals
method and compare all the values inside it. But then, with the equals method overridden, we also have to override thehashcode
method; otherwise, none of the hash-related collection types (HashMap
,HashSet
,HashTable
, and so on) would work. The hashcode
method should return an equal hash value from all objects that the equals
method considers the same. While we are overriding those two methods, let's also override thetoString
method so that the users of our class can get a nice string representation of it. Then, the Java version would look like this (getter
and setter
methods omitted):
public final class User { private String firstName; private String lastName; private int birthYear; public User(String firstName, String lastName, int...