Start learning free

LESSON 189 OF 677 · KOTLIN ESSENTIALS

Data Classes in Kotlin

Lesson

Most of the classes you will ever write do one humble job: hold data. A User is a name and an age; a Point is an x and a y. In Kotlin you can declare such a class in a single line — the properties live right in the parentheses (the primary constructor), no body needed:

class User(val name: String, val age: Int)

But a plain class only stores the data — it doesn't know how to show it or compare it. Every class inherits two defaults: toString prints the class name plus a memory address, and == asks "are these the very same object?" — not "do they hold the same values?".


The trap:

Sooner or later, every Kotlin beginner prints an object, or compares two objects built from identical values — and gets this:

val a = User("Ana", 25)
val b = User("Ana", 25)
println(a)       // expecting the data...
println(a == b)  // expecting true...
User@1540e19d
false

No name, no age — just User@ and a hex address. And two users with the exact same data are "not equal", because the default equals compares identity, not contents.


The fix — one keyword:

Mark the class with data and the compiler generates the useful versions for you, straight from the primary-constructor properties:

data class User(val name: String, val age: Int)

println(User("Ana", 25))                    // User(name=Ana, age=25)
println(User("Ana", 25) == User("Ana", 25)) // true — compares values

You also get copy for free: it clones an object while changing only the properties you name — ana.copy(name = "Bob") keeps the age and swaps the name. Since the properties are val, this is the idiomatic way to get a "changed" version without touching the original.

One rule to remember: every parameter in a data class's primary constructor must be a property. Forget the val and the compiler stops you:

error: primary constructor of data class must only have property ('val' / 'var') parameters.
data class User(name: String)
                ^^^^^^^^^^^^

Assignment
Follow the Coding Tutorial to see all three freebies in action:

  • Declare data class User with val name: String and val age: Int.
  • Create ana = User("Ana", 25) and print her — the generated toString does the formatting.
  • Create twin from the same values and print whether ana == twin.
  • Make bob with ana.copy(name = "Bob") and print him.

The exact expected output is:

ana = User(name=Ana, age=25)
same = true
bob = User(name=Bob, age=25)

Hint
If your output looks like User@1540e19d, you forgot the data keyword. To embed a comparison in a printed string, wrap it in braces: ${ana == twin}.


STEP 1 OF 7
    Ctrl + Enter to check