KtKotlin
IntermediateLesson 9 of 16

Data Classes, Enums & Objects – Kotlin

Data classes with copy, enum classes, singletons, and companion objects.

A data class is meant for pure data: the compiler automatically generates equals, hashCode, toString, copy, and destructuring functions (component1() …).

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

val p = Punkt(1, 2)
println(p)                       // Punkt(x=1, y=2)
println(p == Punkt(1, 2))        // true
val q = p.copy(y = 5)            // copy with changed fields
println(q)                       // Punkt(x=1, y=5)
val (x, y) = q                   // destructuring
println("$x/$y")                // 1/5

enum class defines a fixed set of constants that may have properties and methods. entries returns all values, and a when over an enum must cover all cases.

enum class Wochentag(val arbeitstag: Boolean) {
    MONTAG(true), SAMSTAG(false), SONNTAG(false);

    fun kurz() = name.take(2)
}

for (t in Wochentag.entries) {
    println("$t ${t.arbeitstag} ${t.ordinal} ${t.kurz()}")
}
val text = when (Wochentag.valueOf("MONTAG")) {
    Wochentag.MONTAG -> "start of the week"
    Wochentag.SAMSTAG, Wochentag.SONNTAG -> "weekend"
}
println(text)                    // start of the week

An object is a singleton: exactly one instance, without a constructor. A companion object replaces static members and is ideal for factory functions.

object Logger {
    fun log(msg: String) = println("[LOG] $msg")
}

class Nutzer private constructor(val name: String) {
    companion object {
        const val MAX_LAENGE = 20
        fun erstelle(name: String) =
            Nutzer(name.trim().take(MAX_LAENGE).replaceFirstChar { it.uppercase() })
    }
}

Logger.log("Start")                       // [LOG] Start
println(Nutzer.erstelle("  ada ").name)   // Ada
TipUse data class for all data-transport classes and results. Since all fields must be in the primary constructor, they are not suited to classes with a lot of behavior of their own.