data classes

Data classes are designed to hold data. The compiler automatically derives the following members from all properties declared in the primary constructor and generate:

  • equals() method
  • hashCode() method
  • toString() method
  • componentN() functions corresponding to the properties in their order of declaration
  • copy() function to create a copy

The data keyword marks class as a data class.

data class User(val name: String, val age: Int)

val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)
println(jack) // out: User(name=Jack, age=1)

Data classes have to fulfill the following requirements:

  1. the primary constructor needs to have at least one parameter
  2. all primary constructor parameters need to be marked as val or var

Data classes can not be abstract or open.

The standard library provides the Pair and Triple classes. In most cases, though, named data classes are a better design choice because they make the code more readable by providing meaningful names for the properties.