Data classes
You often create classes whose main purpose is to hold data. In such classes, some standard functionality and utility functions are often mechanically derivable from the data. In Kotlin, these are called data classes and are marked with data
:
The compiler automatically derives the following members from all properties declared in the primary constructor:
equals()
/hashCode()
pairtoString()
of the form"User(name=John, age=42)"
componentN()
functions corresponding to the properties in their order of declaration.copy()
function (see below).
To ensure consistency and meaningful behavior of the generated code, data classes have to fulfill the following requirements:
The primary constructor needs to have at least one parameter.
All primary constructor parameters need to be marked as
val
orvar
.Data classes cannot be abstract, open, sealed or inner.
Additionally, the members generation follows these rules with regard to the members inheritance:
If there are explicit implementations of
equals()
,hashCode()
ortoString()
in the data class body orfinal
implementations in a superclass, then these functions are not generated, and the existing implementations are used.If a supertype has the
componentN()
functions that areopen
and return compatible types, the corresponding functions are generated for the data class and override those of the supertype. If the functions of the supertype cannot be overridden due to incompatible signatures or being final, an error is reported.Providing explicit implementations for the
componentN()
andcopy()
functions is not allowed.
Data classes may extend other classes (see Sealed classes for examples).
Properties declared in the class body
The compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body:
Only the property name
will be used inside the toString()
, equals()
, hashCode()
, and copy()
implementations, and there will only be one component function component1()
. While two Person
objects can have different ages, they will be treated as equal.
Copying
To copy an object for changing some of its properties, but keeping the rest unchanged, use
the copy()
function. For the User
class above, its implementation would be as follows:
You can write the following:
Data classes and destructuring declarations
Component functions generated for data classes enable their use in destructuring declarations:
Standard data classes
The standard library provides Pair
and Triple
. In most cases, though, named data classes are a better design choice, because they make the code more readable by providing meaningful names for properties.