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 properties will be included in the generated implementations of copy(), equals(), hashCode(), and toString().
A data class may also contain properties that are not defined in the primary constructor:
data class Article(val title: String, val author: String) {
var snippet: String = ""
}
Data class properties not defined in the primary constructor will not be included in compiler-generated methods, which we will examine in the next section.