Skip to content
AgileLogics
5 min read

Data Classes

Prerequisites: Constructors, init, and properties

Many classes exist just to hold data. Marking a class data makes Kotlin generate the useful methods for you: toString, equals, hashCode, copy, and destructuring.

Example

data class User(val name: String, val age: Int, val email: String? = null)

fun main() {
    val ada = User("Ada", 36)
    println(ada)

    val same = User("Ada", 36)
    println(ada == same)

    val older = ada.copy(age = 37)
    println(older)

    val (name, age) = ada
    println("$name is $age")

    val users = setOf(ada, same, older)
    println(users.size)
}

Expected output

User(name=Ada, age=36, email=null)
true
User(name=Ada, age=37, email=null)
Ada is 36
2
  • toString prints every property — much more useful than User@1b6d3586.
  • equals compares the property values, so two users with the same data are equal. (For an ordinary class, == only matches the very same object.)
  • hashCode matches equals, so data classes work correctly in sets and as map keys — the set above holds 2 users, not 3.
  • copy creates a new object with some values changed. With val properties, this is how you "modify" data safely.
  • Destructuring unpacks properties in order.

Prefer val properties

Data classes work best as immutable values: declare properties with val, and use copy to produce changed versions. Immutable objects can be shared freely without anyone changing them unexpectedly.

Common mistakes

  • Declaring properties in the class body instead of the constructor. Only constructor properties take part in equals, toString, and copy.
  • Using a data class for something with behavior and identity (a network connection, a game character that changes over time) — an ordinary class fits those better.

Practice

Define data class Book(val title: String, val author: String, val pages: Int). Create a book, print it, then print a copy with 10 more pages.

Show solution
data class Book(val title: String, val author: String, val pages: Int)

fun main() {
    val book = Book("Dune", "Frank Herbert", 412)
    println(book)
    println(book.copy(pages = book.pages + 10))
}
Book(title=Dune, author=Frank Herbert, pages=412)
Book(title=Dune, author=Frank Herbert, pages=422)