Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 134 ยท Classes and Objects

Data Classes

Learn Kotlin data classes: generated equals, hashCode, toString, copy and componentN, destructuring, requirements, shallow copies, data objects and when not to use them.

A huge share of the classes in a real program exist only to carry values: a point, a money amount, a row from a file, a message between two parts of a system. In many languages, writing such a class means a constructor, getters, equals, hashCode and toString, dozens of lines where one wrong line causes a subtle bug. Kotlin's answer is the data class. You write the data, and the compiler writes the boilerplate.

Kotlin
data class Point(val x: Int, val y: Int)

This lesson shows what the compiler generates, how copy and destructuring work, the rules a data class must follow, a classic trap with mutable properties, and when a data class is the wrong tool. It builds on Classes and Properties and Constructors.

What you get for free

Mark a class with data and give it a primary constructor with at least one val or var parameter. The compiler then generates equals(), hashCode(), toString(), copy() and componentN() functions from the properties declared in that constructor:

Kotlin Everything a data class generates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

a and b are two different objects (=== is false) that hold equal data, so == is true and their hash codes agree. This makes data classes excellent keys of maps and elements of sets. The generated toString() prints the class name and every property, which is exactly what you want in logs and in test failures. The details of == and === are covered in Equality and Identity.

Only properties declared in the primary constructor take part in the generated functions. A property declared in the class body is ignored by equals, hashCode, toString, copy and componentN. That is occasionally useful (a cached value that should not affect equality) and occasionally a bug.

Kotlin Properties in the body are ignored

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

toString does not show lastSeen, == ignores it, and copy() starts the copy with the initial value "never" instead of the original's "monday". If a value matters for the identity of the object, it belongs in the constructor.

copy: change without mutating

Prefer val properties in data classes. Instead of changing an object in place, make a copy with some properties replaced. copy() has one parameter per constructor property, each defaulting to the current value, so you name only what changes:

Kotlin copy with named arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This style is called non-destructive update. It keeps old values valid, so you can hold on to the previous state, compare the two, undo, or share an object between threads without locks. It is the foundation of immutable state handling in many Kotlin programs.

Destructuring with componentN

For each constructor property, in order, the compiler generates component1(), component2(), and so on. Kotlin's destructuring declarations call those functions, so you can unpack an object into variables in one line:

Kotlin Destructuring a data class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Destructuring is purely positional. It uses the order of the constructor parameters, not their names. If you later swap two properties of the same type in the class header, every destructuring declaration still compiles but now picks the wrong values. Use destructuring for small, stable classes like Pair or a two-field result, and prefer plain property access for bigger ones. More on this in Pairs, Triples and Destructuring.

The rules a data class must follow

The compiler enforces a few requirements. Break one and you get a clear error:

Kotlin A data class needs constructor properties (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The primary constructor needs at least one parameter, and the message is error: data class must have at least one primary constructor parameter. Every primary-constructor parameter must also be marked val or var:

Kotlin Parameters must be val or var (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports error: primary constructor of data class must only have property ('val' / 'var') parameters. The fix is to write val a: Int. The complete list of rules:

  • the primary constructor has at least one parameter, and each is val or var;
  • a data class cannot be abstract, open, sealed or inner;
  • a data class can implement interfaces and can extend a (non-data) open class, but it cannot be extended;
  • you may write your own toString(), equals() or hashCode() in the body, and the compiler then generates nothing for that function. You may not provide componentN() or copy() yourself.

Because data classes are final, they work best as plain holders of values. If you need a hierarchy of related data shapes, model it with a sealed interface whose cases are data classes.

The shallow copy trap

copy() and equals() are shallow: they work with the property values themselves. If a property refers to a mutable object, the original and the copy share it:

Kotlin Copies share mutable properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Adding "Cy" to the copy also changed the original, because both objects hold the very same list. (Equality here is fine, since MutableList implements value-based equals, so a == b is true. The problem is sharing, not comparison.) To get independent copies, use read-only types and replace the whole collection when it changes: team.copy(members = team.members + "Cy") builds a new list and leaves the old one alone.

A related trap is var properties in data classes whose objects are used as keys in a HashMap or HashSet. Changing a property changes the hash code, and the entry is then lost:

Kotlin Mutating a key breaks the hash set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The set still contains the object (size is 1, and iterating finds it), but contains looks in the bucket for the new hash code and finds nothing. The rule: objects used as keys must be effectively immutable. That is one more reason to write val in data classes by default.

Data objects

A data class needs properties. For a type that has exactly one instance and no data, such as a "loading" state, Kotlin 1.9 added the data object: an object with a readable toString() and a sensible equals()/hashCode().

Kotlin data object versus plain object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A plain object prints as PlainLoading@ plus a hash code, which is unreadable in logs. A data object prints its name. You will see data objects mostly as the "no data" cases next to data classes in sealed hierarchies; see Objects and Companion Objects.

Data classes in everyday code

Because they are so cheap to write, data classes show up everywhere. Here they model a small inventory report, combining copy, collections and destructuring:

Kotlin Data classes in a small report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The computed property total lives in the body, so it adds no storage and does not take part in equality. It cannot get out of sync with price and qty. This mix of constructor properties for the data and body members for derived values is the standard design.

When not to use a data class

  • Entities with identity. A Customer that is still the same customer after changing their address should compare by id, not by every field. Write a regular class and override equals on the id.
  • Classes with behavior and hidden state. A Connection, a Parser, a Cache: there is no sensible copy() or toString().
  • Types you want to evolve compatibly in a library. Adding a property to a data class changes copy() and componentN() signatures, which breaks binary compatibility for other code. Libraries often use regular classes with builders instead.
  • A single value that needs a distinct type. For wrapping one Int or String as a UserId or Email, use a value class.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which functions does the compiler generate for a data class from the primary constructor properties?

    A data class gets equals(), hashCode(), toString(), copy() and one componentN() per primary constructor property.
  2. 2. Given data class P(val x: Int) { var tag = "a" }, two P(1) objects with different tag values are...

    Properties declared in the class body are ignored by the generated functions, so equality looks only at x.
  3. 3. What does val b = a.copy(name = "Zed") do?

    copy creates a new instance; every property not named keeps the old value. It is shallow, so nested mutable objects are shared.
  4. 4. Why is data class Key(var id: Int) dangerous as a HashSet element?

    The set stored the element under its old hash code. After the mutation, contains computes a new hash and looks in the wrong bucket.
  5. 5. Which declaration is NOT allowed?

    Data classes are final: they cannot be open, abstract, sealed or inner. They may implement interfaces and use defaults and var properties.

Summary

  • data class generates equals, hashCode, toString, copy and componentN from the primary constructor properties.
  • Properties in the class body are ignored by all of these functions.
  • Use val properties and copy(...) to update immutably; copy is shallow, so mutable nested objects are shared.
  • Destructuring is positional and relies on the constructor order.
  • Data classes need at least one constructor property, all val/var, and cannot be open, abstract, sealed or inner.
  • Use data object for single-instance types with a readable name; use regular classes for entities, and value classes for single-value wrappers.

Next: Enum Classes