Skip to content
LumenaryAcademy
Practice 60 min

Classes, data classes, sealed classes and objects

Primary constructors and properties, final-by-default inheritance, interface delegation, data and value classes, enums, sealed hierarchies, and objects and companions.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Saying what you mean about your data

A Java class with three fields, a constructor, getters, equals, hashCode and toString easily runs to sixty lines, and every one of those lines must be kept in step whenever a field is added. Kotlin's designers looked at real codebases, noticed how much of that code was ceremony, and gave the language ways to say the common things directly. A class's constructor parameters can be its properties. A class that only holds data says so with one word, data, and gets correct equality and a readable toString for free. A type with a fixed set of alternatives says so with sealed, and the compiler checks that every when handles them all. A singleton is an object, not a pattern.

Kotlin also changes some defaults. Classes and methods are final unless marked open, because inheriting from a class that was not designed for it is a classic source of fragile code. Members are public unless stated otherwise. And properties replace the field-plus-getter-plus-setter trio: you declare what a class has, and decide separately who may change it.

This lesson walks through these tools with three programs: ordinary classes and inheritance, data and value classes, and sealed hierarchies with enums and objects.

DefinitionsH

Definitions

Definition— Primary constructor and properties

class Playlist(val name: String, private val maxSongs: Int = 100) declares a class, its primary constructor, and two properties in one line. A parameter marked val or var becomes a property; one without is just a constructor parameter. init { ... } blocks run as part of construction, typically to validate.

Definition— Property

A named value with a getter (and, for var, a setter). By default a property has a backing field that stores the value; a property with a custom getter and no stored state (val size get() = songs.size) is computed on every access. Accessors can have narrower visibility: var plays = 0; private set.

Definition— Visibility

public (the default, visible everywhere), internal (visible within the same module, such as one Gradle project), protected (the class and its subclasses) and private (the class, or the file for top-level declarations).

Definition— Data class

data class Point(val x: Int, val y: Int) generates equals, hashCode, toString, copy and component1(), component2()... from the properties declared in the primary constructor. Properties declared in the body take no part.

Definition— Sealed class or interface

A type whose direct subtypes are all known at compile time: they must be declared in the same module and package. A when over a sealed type that covers every subtype needs no else.

Definition— Object, companion object and data object

object Name { ... } declares a class and its single instance, created lazily and thread-safely on first use. A companion object inside a class holds members accessed through the class name (Order.create()), the Kotlin counterpart of Java's static members. A data object is an object with a readable toString and sensible equals, ideal as a case of a sealed hierarchy.

Worked examplesH

Classes, inheritance and delegation

kotlin
// A class with a primary constructor, properties, validation and a computed property
class Playlist(val name: String, private val maxSongs: Int = 100) {
    init {
        require(name.isNotBlank()) { "a playlist needs a name" }
        require(maxSongs > 0) { "maxSongs must be positive, was $maxSongs" }
    }

    private val songs = mutableListOf<String>()     // internal state, hidden
    var plays: Int = 0                              // readable everywhere, writable only inside
        private set

    val size: Int get() = songs.size                // computed on every access, no field

    fun add(song: String): Boolean {
        if (songs.size >= maxSongs || song in songs) return false
        songs += song
        return true
    }

    fun play(): String? {
        if (songs.isEmpty()) return null
        val song = songs[plays % songs.size]
        plays++
        return song
    }

    override fun toString() = "Playlist($name, $size songs, $plays plays)"
}

// Interfaces can declare properties and default methods
interface Priced {
    val cents: Long
    fun formatted(): String = "%d.%02d".format(cents / 100, cents % 100)
}

// Classes are final unless marked open; members likewise
open class Ticket(val event: String, override val cents: Long) : Priced {
    open fun label() = "$event ticket"
}

class VipTicket(event: String, cents: Long, val lounge: String) : Ticket(event, cents) {
    override fun label() = super.label() + " with $lounge access"
}

// Delegation: implement an interface by forwarding to another object, overriding just one method
class CountingSet<T>(private val inner: MutableSet<T> = mutableSetOf()) : MutableSet<T> by inner {
    var attempts = 0
        private set

    override fun add(element: T): Boolean {
        attempts++
        return inner.add(element)
    }
}

fun main() {
    val mix = Playlist("Road trip", maxSongs = 3)
    println(listOf("Malaika", "Pata Pata", "Malaika", "Jerusalema", "Sweet Mother").map { mix.add(it) })
    repeat(4) { mix.play() }
    println(mix)
    println(mix.play())

    val tickets: List<Ticket> = listOf(Ticket("Concert", 2_500), VipTicket("Concert", 9_900, "rooftop"))
    for (t in tickets) println("${t.label()}: ${t.formatted()}")

    val seen = CountingSet<String>()
    listOf("a", "b", "a", "c", "b").forEach { seen.add(it) }
    println("${seen.size} distinct of ${seen.attempts} attempts: ${seen.joinToString()}")

    try {
        Playlist(" ")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}
text
[true, true, false, true, false]
Playlist(Road trip, 3 songs, 4 plays)
Pata Pata
Concert ticket: 25.00
Concert ticket with rooftop access: 99.00
3 distinct of 5 attempts: a, b, c
a playlist needs a name

Playlist shows the shape of most Kotlin classes. The constructor line declares name as a public read-only property and maxSongs as a private one with a default. The init block validates with require, which throws IllegalArgumentException with the given message when its condition is false (its sibling check throws IllegalStateException, for broken object state rather than bad arguments). songs is private, so the only way to change the list is through add, which keeps the "at most maxSongs, no duplicates" rule. plays can be read by anyone but set only inside the class (private set). size has no backing field at all; it is computed from songs whenever it is read. From outside, all of them look the same: mix.name, mix.plays, mix.size.

Inheritance is opt-in. Ticket is marked open so it can be extended, and label() is open so it can be overridden; without those words, the compiler says "this type is final, so it cannot be extended". VipTicket passes its constructor arguments up with : Ticket(event, cents) and calls the inherited implementation with super.label(). override is a required keyword, not an optional annotation, so overriding by accident (or failing to override because of a typo) is impossible. Ticket implements the cents property declared by the interface Priced directly in its constructor, with override val, and inherits formatted().

Delegation with by. CountingSet implements the whole MutableSet interface (more than a dozen methods) in one line: : MutableSet<T> by inner makes the compiler generate a forwarding method for each, calling inner. It then overrides just add. This is composition with none of the boilerplate, the alternative that Kotlin offers to inheriting from a concrete collection class. Note one subtlety: methods of Any such as toString are not delegated, which is why the program prints the set's contents with joinToString() rather than relying on toString().

Worked examplesH

Properties with behaviour: setters and lazy values

Because callers always go through a property's accessors, you can add behaviour to a property later without changing any code that uses it. Two forms are especially common:

kotlin
class Thermostat(initial: Double) {
    // A custom setter that validates; `field` is the property's backing field
    var targetCelsius: Double = initial
        set(value) {
            require(value in 5.0..30.0) { "target out of range: $value" }
            field = value
        }

    // Computed once, on first access, then cached (thread-safe by default)
    val report: String by lazy {
        println("  (building report)")
        "Thermostat set to $targetCelsius C"
    }
}

fun main() {
    val t = Thermostat(21.0)
    t.targetCelsius = 23.5
    try {
        t.targetCelsius = 80.0
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
    println(t.report)
    println(t.report)
}
text
target out of range: 80.0
  (building report)
Thermostat set to 23.5 C
Thermostat set to 23.5 C

Inside a custom accessor, the keyword field refers to the stored value; writing targetCelsius = value there instead would call the setter again, forever. The assignment t.targetCelsius = 23.5 looks like a field write but runs the setter, so the rejected value never gets stored.

by lazy { ... } is a delegated property: the getter is handed to an object (here, the standard library's lazy holder) that runs the block on first access and remembers the result. The "(building report)" line appears once, although report is read twice. Lazy properties suit values that are expensive to compute and may never be needed. Note the trade-off this example exposes: the report captured the target at the moment it was first built, and would not notice a later change. Use lazy for values that do not depend on changing state.

Worked examplesH

Data classes and value classes

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

data class Student(val name: String, val grades: List<Int>) {
    val average: Double get() = grades.average()      // declared in the body: not part of equals
}

@JvmInline
value class StudentId(val raw: Int)                    // a type-safe wrapper with no run-time cost

fun lookUp(id: StudentId): String = "student #${id.raw}"

fun main() {
    val p = Point(3, 4)
    val q = Point(3, 4)
    println(p)                                          // generated toString
    println("${p == q} ${p === q}")                     // generated equals: same contents
    println(setOf(p, q, Point(0, 0)).size)              // generated hashCode: works in sets

    val moved = p.copy(y = 10)                          // a modified copy; p is unchanged
    println("$p -> $moved")

    val (x, y) = moved                                  // destructuring via component1(), component2()
    println("x=$x y=$y")

    val wanjiru = Student("Wanjiru", listOf(80, 92, 71))
    println("${wanjiru.name}: %.1f".format(java.util.Locale.ROOT, wanjiru.average))

    // copy is shallow: the list is shared, not duplicated
    val twin = wanjiru.copy(name = "Twin")
    println(wanjiru.grades === twin.grades)

    println(lookUp(StudentId(1042)))
    // lookUp(1042)  would not compile: an Int is not a StudentId
}
text
Point(x=3, y=4)
true false
2
Point(x=3, y=4) -> Point(x=3, y=10)
x=3 y=10
Wanjiru: 81.0
true
student #1042

A data class is Kotlin's answer to "a value with a few named parts". Two Points with the same coordinates are ==, hash the same, and collapse to one element in a set. copy makes a modified copy with named arguments, the idiomatic way to "change" an immutable value. Destructuring (val (x, y) = moved) uses the generated component1() and component2() functions, in constructor order, which is also what makes for ((key, value) in map) work.

Good data classes are immutable: all properties val, and their types immutable too (List rather than MutableList). Then copies can be shared freely. Remember that copy is shallow: twin and wanjiru share one grades list. With a read-only List that is harmless; with a MutableList it would be a trap.

A value class wraps a single value to give it a distinct type. StudentId and a plain Int cannot be confused: passing 1042 where a StudentId is expected does not compile, and a function taking (StudentId, CourseId) cannot have its arguments swapped by accident. On the JVM the compiler usually erases the wrapper and passes the raw Int, so the safety costs nothing at run time. The @JvmInline annotation is required for value classes on the JVM.

ComputationC

Enums, sealed hierarchies and objects

kotlin
enum class Tier(val discountPercent: Int) {
    BRONZE(0), SILVER(5), GOLD(10);

    fun next(): Tier? = entries.getOrNull(ordinal + 1)      // entries: Kotlin 1.9+
}

// A sealed hierarchy: every possible result of loading a page
sealed interface PageResult {
    data class Loaded(val html: String, val millis: Long) : PageResult
    data class Failed(val status: Int, val reason: String) : PageResult
    data object NotModified : PageResult                    // a singleton with a nice toString
}

fun summary(r: PageResult): String = when (r) {             // no else: the compiler checks all cases
    is PageResult.Loaded -> "loaded ${r.html.length} chars in ${r.millis} ms"
    is PageResult.Failed if r.status >= 500 -> "server error ${r.status}: ${r.reason}"
    is PageResult.Failed -> "client error ${r.status}"
    PageResult.NotModified -> "cached copy is still fresh"
}

// An object declaration: exactly one instance, created on first use
object IdGenerator {
    private var last = 0
    fun next(): Int = ++last
}

// A companion object holds factory functions and constants for its class
class Order private constructor(val id: Int, val tier: Tier) {
    companion object {
        const val MAX_ITEMS = 50
        fun create(tier: Tier = Tier.BRONZE) = Order(IdGenerator.next(), tier)
    }

    override fun toString() = "Order#$id(${tier.name.lowercase()}, ${tier.discountPercent}% off)"
}

fun main() {
    println(Tier.entries)
    println("${Tier.SILVER.next()} ${Tier.GOLD.next()}")
    println(Tier.valueOf("GOLD").discountPercent)

    val results = listOf(
        PageResult.Loaded("<html>hello</html>", 42),
        PageResult.Failed(503, "maintenance"),
        PageResult.Failed(404, "not found"),
        PageResult.NotModified,
    )
    results.forEach { println(summary(it)) }
    println(PageResult.NotModified)

    println(Order.create())
    println(Order.create(Tier.GOLD))
    println("max items: ${Order.MAX_ITEMS}")

    // An object expression: an anonymous one-off implementation
    val reversed = object : Comparator<String> {
        override fun compare(a: String, b: String) = b.compareTo(a)
    }
    println(listOf("kiwi", "apple", "mango").sortedWith(reversed))
}
text
[BRONZE, SILVER, GOLD]
GOLD null
10
loaded 18 chars in 42 ms
server error 503: maintenance
client error 404
cached copy is still fresh
NotModified
Order#1(bronze, 0% off)
Order#2(gold, 10% off)
max items: 50
[mango, kiwi, apple]

Enums in Kotlin are full classes: Tier has a property per constant and a method. entries (Kotlin 1.9) lists the constants in order; it replaces the older values(), which allocated a new array on every call.

Sealed interfaces model "one of these, and nothing else". Each case can carry different data: a loaded page has HTML and a time, a failure has a status and a reason, and "not modified" carries nothing, so it is a data object. The when in summary has no else, so if someone later adds data class Redirected(...) to the hierarchy, every such when stops compiling until it handles the new case. Guards (is PageResult.Failed if r.status >= 500) split one case further. This is the same data-oriented style that Java adopted with records and sealed interfaces, and Kotlin code uses it everywhere: for UI states on Android, for results of operations, for messages between components.

Objects. IdGenerator is a singleton: the language guarantees one instance, created thread-safely the first time it is used. Order's constructor is private, so the only way to create an order is the factory in its companion object, which assigns an ID. const val declares a compile-time constant. Companion members are called through the class name, like Java's static members, but the companion is a real object that can implement interfaces. Finally, object : Comparator<String> { ... } is an object expression, an anonymous class created on the spot; for a single-method interface like this one, a lambda (compareByDescending { it } or Comparator { a, b -> b.compareTo(a) }) is usually shorter.

ExplanationH

Design notes

  • Final by default is a feature. It follows the long-standing advice to design classes for inheritance or else prohibit it. Mark a class open only when you have thought about how subclasses may change it, and prefer interfaces plus delegation for reuse.
  • Choose the class kind by what the type means. A value with no identity (a coordinate, a money amount, a message): data class, immutable. A wrapper that adds type safety to a primitive: value class. A fixed set of constants: enum class. A fixed set of alternatives with different data: sealed interface with data classes and data objects. Something with identity and changing state (a playlist, a connection): a plain class with private state.
  • Keep data classes small and flat. Business logic that needs several collaborators belongs in ordinary classes; a data class with twenty properties and a dozen methods is usually two or three classes in disguise.
  • Use object sparingly for state. A singleton holding mutable state, like IdGenerator, is global state with all its problems: hard to test, shared between threads. For stateless utilities, top-level functions are usually simpler than an object.
Common misconceptionsH

Common misconceptions

Misconception

"Every property of a data class takes part in equals." Only those in the primary constructor do. A var declared in the body is ignored by equals, hashCode, toString and copy.

Misconception

"copy makes a deep copy." It copies the property values, which for objects are references. Nested mutable objects are shared between the original and the copy.

Misconception

"A companion object is the same as Java's static." It is an object instance. Java code reaches its members through Order.Companion.create() unless they are annotated with @JvmStatic (or are const).

Misconception

"Kotlin classes can be subclassed as in Java." They are final unless declared open. This is also why some Java frameworks that generate subclasses at run time need a compiler plugin (such as kotlin-allopen, configured by the Spring plugin) when used with Kotlin.

Exercises

Exercises

1. Classes, data classes, sealed classes and objects

Warm-upComputational

What does this program print?

data class Rgb(val r: Int, val g: Int, val b: Int)

fun main() {
    val c = Rgb(10, 20, 30).copy(g = 0)
    println(c)
}

2. Classes, data classes, sealed classes and objects

CoreComputational

What does this program print?

data class Tag(val name: String) {
    var uses = 0
}

fun main() {
    val a = Tag("kotlin")
    a.uses = 5
    val b = Tag("kotlin")
    println(setOf(a, b).size)
}

3. Classes, data classes, sealed classes and objects

CoreComputational

What does this program print?

object Counter {
    var n = 0
}

fun main() {
    repeat(3) { Counter.n++ }
    val c = Counter
    c.n += 10
    println(Counter.n)
}

4. Classes, data classes, sealed classes and objects

CoreComputational

What does this program print? (It uses 3.0 for π to keep the arithmetic simple.)

sealed interface Shape
data class Circle(val r: Double) : Shape
data class Square(val side: Double) : Shape
data object Empty : Shape

fun area(s: Shape): Double = when (s) {
    is Circle -> 3.0 * s.r * s.r
    is Square -> s.side * s.side
    Empty -> 0.0
}

fun main() {
    println(listOf(Circle(1.0), Square(2.0), Empty).sumOf { area(it) })
}

5. Classes, data classes, sealed classes and objects

Warm-upHuman

Why does class Base followed by class Derived : Base() fail to compile?

Choose one

6. Classes, data classes, sealed classes and objects

Warm-upComputational

With the lesson's enum class Tier { BRONZE, SILVER, GOLD } (and its discounts), what does println(Tier.entries.joinToString("") { it.name.first().toString() }) print?

7. Classes, data classes, sealed classes and objects

StretchHuman

About class CountingSet<T>(private val inner: MutableSet<T>) : MutableSet<T> by inner, which statements are true? Choose all that apply.

Choose all that apply

Further reading and resources