The Analogy: Building Codes and the Show-Home Template
A published building code is a document, not a building. The fire-safety code lists requirements every structure must meet -- exits must be marked, alarms must sound -- without owning a single brick, a plot of land, or an address. Some of its clauses are bare mandates that each builder must satisfy in their own way, while others are standard boilerplate the code supplies verbatim unless a builder has good reason to write their own wording. A Kotlin interface is exactly this kind of code: it declares members a class must provide, it can ship default implementations for some of them, but it holds no state of its own and has no constructor, because a standard is a set of obligations, not a physical thing.
The power of a code is that one structure can comply with many at once. A single building answers to the fire code, the accessibility code, and the energy code simultaneously, meeting every obligation each one imposes. A Kotlin class implements as many interfaces as it likes, absorbing the contract of each, which is how the language offers multiple inheritance of behaviour without the hazards of multiple inheritance of state. The building does not become three buildings; it remains one structure that happens to satisfy three separate standards.
An abstract class is a different instrument: the partially-constructed show-home template. Unlike a code, it is a real structure-in-progress -- it has foundations poured and framing raised, which is to say it carries actual state and runs a constructor. It leaves certain rooms deliberately unfinished for the buyer to fit out, the way an abstract member leaves a method body for a subclass to supply. The crucial trade is that a builder can comply with many codes but can build on only one template, because you cannot pour a house onto two independent foundations. Kotlin mirrors this precisely: a class may implement many interfaces but may extend at most one class.
The failure that ruins the job is the builder who tries to store the building's actual address inside the fire code itself. The code is a shared document held by every building in the district; it has nowhere to keep one building's private details, and writing them there would corrupt the standard for everyone. In Kotlin this surfaces as the rule that an interface property has no backing field -- it can require a value and even compute one, but it cannot store per-object state. The opposite mistake is cramming every shared feature into one enormous abstract base to get common state for free, only to discover later that a class needs to satisfy two such bases at once -- an impossibility with single inheritance, and precisely the situation that composing small interfaces would have avoided.
Syntax or Core Structure
An interface declares members, some abstract and some with default bodies. A class that implements it uses override for every member, exactly as with class inheritance, but it may implement several interfaces at once.
interface Alarmed {
val zone: String // abstract property, no backing field
fun trigger(): String // abstract method
fun status(): String = "zone " + zone + " armed" // default method
}
class Warehouse(override val zone: String) : Alarmed {
override fun trigger(): String = "siren in " + zone
}
fun main() {
val w: Alarmed = Warehouse("bay-3")
println(w.status())
println(w.trigger())
}
Output:
zone bay-3 armed
siren in bay-3
Alarmed requires a zone property and a trigger method, and supplies a default status. Warehouse satisfies zone by declaring override val zone right in its constructor -- the interface property has no field, so the implementing class provides the actual storage. It overrides trigger but inherits status unchanged. Calling through the Alarmed-typed reference, status() uses the default body (reading the overridden zone to print "zone bay-3 armed"), while trigger() runs the class's own implementation. The interface named the obligations; the class supplied the state and the behaviour.
Technical Depth: Contracts, Composition, and Conflicts
Interface versus abstract class
The two tools overlap but differ on the one axis that matters most: state. The table lays out where each is the right choice.
| Trait | Interface | Abstract class |
|---|---|---|
| Can hold state (backing fields) | no | yes |
| Has a constructor | no | yes |
| A class can have many | yes | no (single inheritance) |
| Default method bodies | yes | yes |
| Property with backing field | no (getter only) | yes |
| Models | a capability / contract | a partial base with shared state |
Reach for an interface when you are describing what a type can do and expect many unrelated types to do it. Reach for an abstract class when subclasses genuinely share stored state and construction logic, and you are certain a single base is enough.
Composing several interfaces
A class can satisfy multiple contracts at once, absorbing the defaults of each.
interface Loggable {
fun logLine(): String
}
interface Timestamped {
val seq: Int
fun stamp(): String = "#" + seq
}
class Event(override val seq: Int, private val msg: String)
: Loggable, Timestamped {
override fun logLine(): String = stamp() + " " + msg
}
fun main() {
val e = Event(seq = 7, msg = "startup")
println(e.stamp())
println(e.logLine())
}
Output:
#7
#7 startup
Event implements both Loggable and Timestamped; it overrides logLine, provides the seq property, and inherits stamp unchanged from Timestamped. The direct call stamp() uses the inherited default and prints "#7". The overridden logLine() composes that same inherited stamp() ("#7") with " startup" to print "#7 startup". One class satisfied two contracts, reusing the default from one while supplying its own body for the other.
Resolving a diamond with super<T>
When two interfaces supply defaults for the same signature, the implementing class must resolve the clash explicitly, naming which one it means with super<Interface>.
interface North {
fun mark(): String = "N"
}
interface South {
fun mark(): String = "S"
}
class Compass : North, South {
override fun mark(): String =
super<North>.mark() + super<South>.mark()
}
fun main() {
println(Compass().mark())
}
Output:
NS
Both North and South define a default mark, so Compass inherits an ambiguous signature and is forced to override it. Inside the override, super<North>.mark() selects the North default ("N") and super<South>.mark() selects the South default ("S"); concatenating them yields "NS". The angle-bracket syntax is how Kotlin lets you reach a specific inherited default when more than one applies -- the builder naming which code's clause governs.
A single-method interface as a lambda
An interface with exactly one abstract method can be marked fun interface, which lets Kotlin convert a lambda directly into an implementation -- a SAM (single abstract method) conversion. This keeps a one-method contract lightweight at the call site.
fun interface Validator {
fun check(text: String): Boolean
}
fun countValid(items: List<String>, v: Validator): Int =
items.count { v.check(it) }
fun main() {
val nonEmpty = Validator { it.isNotEmpty() }
val words = listOf("a", "", "cat", "")
println("valid: " + countValid(words, nonEmpty))
}
Output:
valid: 2
Because Validator is a fun interface with the single method check, the lambda { it.isNotEmpty() } is converted into a Validator instance without a named class or an object expression. countValid then applies it to each item; of the four entries, only "a" and "cat" are non-empty, so the count is 2. SAM conversion is the bridge between Kotlin's interface contracts and its lambda syntax, ideal when a contract is genuinely one method wide.
Real World Example: A Summarizable Shopping Basket
A retail app wants every displayable collection to produce a one-line summary. Rather than bake that into a base class, it defines a Summarizable interface with a default summary built from an abstract label and an abstract size. A Basket implements the interface and adds items over its lifetime.
interface Summarizable {
val label: String
val size: Int
fun summary(): String = label + ": " + size + " items"
}
class Basket(override val label: String) : Summarizable {
private val items = mutableListOf<String>()
override val size: Int = items.size // snapshot at construction
fun add(item: String) { items.add(item) }
fun actualSize(): Int = items.size
}
fun main() {
val b = Basket("weekly")
b.add("bread")
b.add("milk")
println(b.summary())
println("actual items: " + b.actualSize())
}
Output:
weekly: 0 items
actual items: 2
The design reads well at first glance. Summarizable names two obligations and supplies the formatting once, so any collection type gets a consistent summary for free. Basket provides label through its constructor, backs its contents with a private items list, and satisfies size with an override. Two items go in, and actualSize() -- which reads items.size when called -- correctly reports 2.
But summary() reports "weekly: 0 items", contradicting the real count on the very next line. The cause is the shape of the size override: override val size: Int = items.size is a property initializer, evaluated exactly once during construction. At that moment items is empty, so size is frozen at 0 and never changes, no matter how many items are added later. The interface's default summary faithfully reads that stale value.
This is the genuine design flaw, and it is precisely the trap the interface's own nature warns about. An interface property has no backing field; it is meant to be computed on each read, exactly as a code clause is re-checked against the current building rather than a snapshot taken the day it was written. Implementing it with a stored initializer defeats that intent and captures a one-time value. The fix is a custom getter: override val size: Int get() = items.size, which recomputes on every access and makes summary report "weekly: 2 items". The limitation to note is broader -- default interface methods can only ever be as correct as the properties they read, and because the interface cannot hold or validate state itself, a single mis-implemented property silently corrupts every default that depends on it.
Common Mistakes
- Trying to store state in an interface. An interface property has no backing field, so
var count = 0inside an interface will not compile. Interfaces declare obligations; the implementing class supplies the storage.
- Implementing an interface property with an initializer instead of a getter.
override val size = items.sizesnapshots the value once at construction. If it should track changing state, writeoverride val size get() = items.sizeso it recomputes on each read.
- Reaching for an abstract class when an interface fits. If types that share no common base need the same capability, an abstract class forces an artificial inheritance line. An interface lets unrelated types opt in without a shared ancestor.
- Ignoring a diamond conflict. When two interfaces supply defaults for the same signature, the class must override and resolve it with
super<Interface>.member(). Leaving it unresolved is a compile error, not a silent pick.
- Assuming a default method can be as capable as a class method. Defaults cannot access private state of the implementer and cannot cache across calls, because the interface has no fields. Push anything stateful into the class.
- Forgetting
overrideon interface members. Just as with class inheritance, every implemented member needsoverride. Interface membership does not exempt you from the keyword.
- Using an abstract class only to share one default method. If there is no shared state or constructor logic, an interface with a default body achieves the same reuse without consuming the single inheritance slot.
- Declaring an interface method
open. Interface members are open by default; theopenkeyword is redundant there and only adds noise. Reserveopenfor class members.
- Expecting interface defaults to run first during construction. An interface has no constructor and no initialization phase; its defaults run only when called. Do not rely on any ordering between interface defaults and a class's
initblock.
Best Practices
- Use interfaces to model capabilities that many unrelated types can share, and abstract classes only when subclasses genuinely share stored state and construction.
- Implement interface properties with getters when they reflect changing state, reserving initializers for values that are truly fixed at construction.
- Keep interfaces small and focused on one capability, so a class can compose exactly the contracts it needs rather than inheriting a monolith.
- Provide default methods for behaviour that is uniform across implementers, and leave genuinely varying behaviour abstract.
- Resolve diamond conflicts explicitly with
super<Interface>, making it obvious which inherited default you intend. - Prefer composing several interfaces over deep abstract-class hierarchies, preserving the single inheritance slot for a real shared base.
- Do not put mutable or per-instance state in default methods; delegate anything stateful to the implementing class.
- Name interfaces for the capability they grant (
Comparable,Closeable,Summarizable) so implementing them reads as a statement of what a type can do.
Practice Exercises
- Define an interface
Playablewith an abstractfun play(): Stringand a defaultfun describe(): Stringbuilt from an abstractval title. Implement it in aSongclass and confirm the defaultdescribereads the overriddentitle.
- Reproduce the stale-property flaw: implement an interface
Counted(abstractval size) in a class backed by a mutable list, first with an initializer and then with a getter. Add items and show that only the getter version reports the live count.
- Create two interfaces that both declare a default
fun tag(): Stringwith different results, implement both in one class, and resolve the conflict so the class returns their concatenation usingsuper<Interface>.
- Model a
Documentthat implements bothPrintableandEmailableinterfaces, each with one abstract method. Show that a single class satisfies both contracts and that aPrintable-typed reference can still call the printing method.