Data Class Rules

Requirements

  • The primary constructor needs at least one parameter, and every parameter must be val or var.
  • Data classes cannot be abstract, open, sealed or inner.
  • They can implement interfaces and extend other (open) classes.
  • Only properties declared in the primary constructor are used in the generated functions.

Properties in the Body are Ignored

Example

viewCount is declared in the body, so equals and toString ignore it.

data class Article(val id: Int, val title: String) {
    var viewCount = 0
}

fun main() {
    val a = Article(1, "Kotlin Tips")
    val b = Article(1, "Kotlin Tips")
    a.viewCount = 500
    println(a)
    println("equal? ${a == b}")
}

Output

Article(id=1, title=Kotlin Tips)
equal? true

data object

For a singleton that is used like data (for example a "Loading" state), use data object (Kotlin 1.9+). It gets a clean toString().

Example

object PlainLoading
data object Loading

fun main() {
    println(Loading)
    println(PlainLoading.toString().startsWith("PlainLoading@"))
}

Output

Loading
true