Object-oriented and functional Kotlin programming
Domain 2 tests how you design Kotlin types and compose behavior with lambdas. Expect questions on constructor mechanics, inheritance defaults, data and sealed classes, extension resolution, and higher-order functions.
Class design
A primary constructor parameter becomes a property only when marked val or var; otherwise it is available only in initializers and init blocks. init blocks and property initializers run in declaration order. A secondary constructor must delegate to the primary constructor with this(...) or to another secondary constructor.
Classes and members are final by default. Inheritance requires open on the superclass, and overrides require override; an override remains open unless marked final. Interface members are open, and an interface can provide a default implementation.
A data class needs at least one primary-constructor parameter, all of which must be val or var. The compiler generates equals, hashCode, toString, copy, and componentN. A sealed hierarchy restricts direct subclasses and enables exhaustive when.
Functional composition
A function type such as (Int) -> String can be stored, passed, and returned. Lambdas capture surrounding variables; a trailing lambda can move outside the parentheses. Extension functions are resolved statically: a member function with the same signature always wins, and an extension cannot override a member.
Worked example
data class Item(val sku: String, val qty: Int)
fun restock(items: List<Item>, amount: Int): List<Item> =
items.map { it.copy(qty = it.qty + amount) }
Reasoning: map produces a new list; copy produces a new Item with qty changed while reusing sku; the original list and items remain unchanged. The lambda's implicit parameter is it.
Traps
Using a data class with mutable properties as a map key breaks lookups after mutation because hashCode changes. Forgetting open on a superclass is a compile error. Also remember that generated data-class equality compares array properties by reference, not content.