Kotlin Classes

Kotlin classes are concise but expressive. Data classes and sealed types are especially useful for model-heavy applications.

Classes

A Kotlin class declares its primary constructor and properties right in the class header, eliminating repetitive field assignments. Classes are final (closed to inheritance) by default; you must opt in with open when designing a base class:

class User(val name: String, var active: Boolean = true) {
    fun summary(): String = "$name (active=$active)"
}

val dev = User("Ada")
println(dev.summary())

Data classes

When a class exists primarily to hold state (DTOs, events, configuration), mark it data class. The compiler generates structural equals, hashCode, toString, destructuring componentN functions, and an immutable-friendly copy() method:

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

val origin = Point(0, 0)
val moved = origin.copy(x = 5)   // creates a new instance without mutating origin
val (px, py) = moved             // destructuring declaration
println("$moved -> x=$px, y=$py")

Sealed types

A sealed interface or sealed class restricts all direct subclasses to the same package and module at compile time. Because the compiler knows every possible subtype, when expressions over a sealed hierarchy are checked for exhaustiveness without needing an error-hiding else branch:

sealed interface LoadState {
    data object Loading : LoadState
    data class Ready(val count: Int) : LoadState
    data class Failed(val reason: String) : LoadState
}

fun render(state: LoadState): String = when (state) {
    LoadState.Loading -> "Loading..."
    is LoadState.Ready -> "Loaded ${state.count} items"
    is LoadState.Failed -> "Error: ${state.reason}"
}

Interfaces

Interfaces define capability contracts and can include default method implementations and abstract properties without holding backing state. A class can implement multiple interfaces, making composition cleaner than deep inheritance trees.

Practice

Model a small domain state machine using Kotlin's class constructs:

  1. Define a data class OrderItem(val sku: String, val qty: Int) and test copy() and structural ==.
  2. Create a sealed interface PaymentResult with Approved and Declined subtypes and handle both in a when expression.
  3. Explain why Kotlin makes classes final by default unless marked open.