Skip to content
Learn Netverks

Lesson

Step 13/36 36% through track

data-classes

Data classes

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Data classes: the syntax, patterns, and safety habits you need before advancing in Kotlin.

Data classes replace Java boilerplate for DTOs—equals/hashCode/toString generated automatically.

You will apply Data classes in contexts like: Android apps, Spring services, and shared KMP modules.

Write Kotlin in main.kt with fun main(), click Run on server—the dev runner kotlinc compiles to a JVM jar and java runs it; use println for output (requires JDK + kotlinc; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Data classes are Kotlin's answer to Java records and C# records for immutable-ish carriers: the compiler generates equals, hashCode, toString, and copy when you mark a class with data.

Syntax and copy

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

val a = Point(1, 2)
val b = a.copy(y = 5)

Data classes must have at least one primary constructor parameter. They cannot be abstract, open, sealed, or inner.

Destructuring

val (x, y) = point uses component functions component1(), component2(), …—handy for tuples-like returns without a separate Pair type.

Important interview questions and answers

  1. Q: Data class vs regular class?
    A: Data classes auto-generate structural equality and copy; use them for DTOs and value-like aggregates, not deep inheritance trees.
  2. Q: Are data class properties always immutable?
    A: No—var in the header is allowed, but val is idiomatic for predictable equality.

Self-check

  1. What method creates a modified duplicate?
  2. Can a data class be open?

Tip: Use copy() for immutable-style updates instead of mutating shared DTOs in concurrent code.

Interview prep

What is generated?

equals, hashCode, toString, copy, componentN.

When to use?

DTOs and value-like aggregates—not deep inheritance.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • copy() use?
  • componentN destructuring?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump