We often create classes that are meant to hold data and nothing else. In these cases, we may often want to override specific methods such as equals() and hashCode() so these data classes can be compared to one another. In Kotlin, this type of class is supported natively.
Understanding data classes
Creating a data class
To create a data class, we can add the data keyword to a class declaration as long as the class follows several specific rules:
- It is a primary constructor with at least one property
- It cannot be a sealed class, open, inner, or abstract
In this example, we define a data class, Article, which contains two primary constructor properties:
data class Article(val title: String, val author: String)
Primary constructor...