Data Classes
We'll cover the following
What is a data class
Much like the case classes of Scala, the data classes of Kotlin are specialized classes that are intended to carry mostly data rather than behavior. The primary constructor is required to define at least one property, using val
or var
. Non-val
or var
parameters aren’t allowed here. You may add other properties or methods to the class, within the body {}
, if you desire.
For each data class Kotlin will automatically create the equals()
, hashCode()
, and toString()
methods. In addition, it provides a copy()
method to make a copy of an instance while providing updated values for select properties. It also creates special methods that start with the word component
—-component1()
, component2()
, and so on—to access each property defined through the primary constructor. We’ll refer to these methods as componentN()
methods for convenience.
Here’s an example data class that represents a task or a to-do item, annotated with the data keyword to convey the intent:
// taskdataclass.kts
data class Task(val id: Int, val name: String,
val completed: Boolean, val assigned: Boolean)
Any property defined within the class body {}
, if present, will not be used in the generated equals()
, hashCode()
, and toString()
methods. Also, no componentN()
method will be generated for those.
Creating an object of a data class
Continuing with the same example, let’s create an object of the data class and exercise one of the generated methods, toString()
.
Get hands-on with 1200+ tech skills courses.