Data Classes

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 ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.