Kotlin: Classes & Data Classes
What you will learn
Kotlin's concise class syntax, how constructor parameters become properties, and what you get for free with data class.
Classes with constructor properties
Kotlin combines constructor, property declaration, and initializer into one expression:
class Person(val name: String, var age: Int)
val alice = Person("Alice", 25)
println(alice.name) // "Alice" (getter)
alice.age = 26 // setter works because var
val in the constructor creates a read-only property (getter only). var creates a mutable property (getter + setter).
Data classes
Add data before class and Kotlin automatically generates equals(), hashCode(), toString(), copy(), and componentN():
data class User(val id: Int, val email: String)
val u1 = User(1, "[email protected]")
val u2 = User(1, "[email protected]")
println(u1 == u2) // true (structural equality, not reference)
println(u1.toString()) // User(id=1, [email protected])
val u3 = u1.copy(email = "[email protected]") // copy with modification
This replaces dozens of lines of boilerplate that you'd write in Java.
Sealed classes (restricted hierarchies)
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
}
Sealed classes work with when expressions — the compiler checks that every subclass is handled.
Common mistakes
- Forgetting that
data classproperties must be declared in the primary constructor — properties in the body are not included inequals/toString - Using
==vs===—==callsequals()(structural),===checks reference identity - Thinking
data classmakes deep copies —copy()does a shallow copy; nested objects are still shared
Quick check below!