Thuta Learning
Kotlin
IntermediateProgrammingBeginner

Interfaces

KotlinLesson 1730 min

What you'll walk away with

  • Declare an interface with abstract members and implement it with override
  • Write default method bodies and abstract or computed properties inside an interface
  • Resolve a clash between two interfaces with super<Type>.member()
  • Choose between an interface and an abstract class, and program against the interface type

Explain it simply

Explain it simply

An interface is a contract that names what a class must be able to do, without saying how. A wall socket is a good picture: it promises a standard shape of holes, and any plug that fits works, whether it belongs to a lamp or a phone charger. A class that implements the interface promises to supply every function the contract lists. Code that knows only the contract, the socket, works with any class that signs it, including classes that do not exist yet.

Unlike a parent class, a Kotlin class can sign as many contracts as it likes, so you can describe a Duck as both a Swimmer and a Flyer.

Problem → Why → Solution

The problem: one overload per class and no mixed lists

Your delivery app has Car and Bike classes that can both drive(). To start a trip you write startTrip(car: Car) and startTrip(bike: Bike), and a third copy when a Scooter arrives. You also cannot put a car and a bike in the same list without giving up on types and using List<Any>, and then every item must be checked and cast before use.

no-contract.kt
class Car { fun drive() = println("Driving a car") }
class Bike { fun drive() = println("Pedalling a bike") }

fun startTrip(car: Car) = car.drive()
fun startTrip(bike: Bike) = bike.drive()   // one more copy for every new vehicle

fun main() {
    val fleet: List<Any> = listOf(Car(), Bike())
    for (v in fleet) {
        // v.drive()   // not allowed: v is only an Any, and Any has no drive()
    }
}

Why do these classes not fit together?

The classes share a capability, but the type system does not know it. An interface gives that shared capability a name, Drivable, so startTrip(vehicle: Drivable) accepts every present and future implementer, and List<Drivable> holds mixed vehicles safely. The caller depends on the contract, not on a concrete class, which also makes fakes easy to supply in tests.

Core concept: an interface is a contract that holds no state

Declaring an interface is like declaring an abstract class, with three differences that matter. It cannot keep state: no property of an interface has a backing field. A class may implement many interfaces but extend only one class. And implementing needs no constructor call: class Car : Drivable has no parentheses after Drivable. Members are public, those without a body are abstract, and the implementer marks each one override; forgetting is an error, and leaving one out is another: "class 'Car' is not abstract and does not implement abstract member".

Interface members can have bodies. A function with a body is a default implementation that implementers inherit and may override, and a property can declare a getter, as in val label: String get() = "payment in $currency". A property without a getter is abstract: implementers supply it, in the body or straight from their constructor with override val. You cannot give an interface property an initial value; the compiler says "property initializers in interfaces are prohibited".

When two interfaces offer the same function with a body, a class implementing both must pick: the compiler reports an error such as "class 'C' must override 'hello' because it inherits multiple interface methods for it". Inside the override you choose with super<Swimmer>.move(), or call both. Interfaces can also extend other interfaces (interface Greeter : Named), and an anonymous implementation is written object : Greeter { ... }.

Interface or abstract class? Reach for an interface by default: it describes a capability, allows several at once, and carries no state that could be inherited by accident. Use an abstract class when children share state or constructor logic, such as a name stored once. Then program against the interface type: parameters and variables should say Drivable, not Car, so the caller can swap implementations.

Featureinterfaceabstract class
State (backing fields)NoYes
How many a class can useManyOne
ConstructorNoneYes, called by children
Default member bodiesYesYes
Mental model: a socket and its plugs
  1. Interface lists the required members
  2. Each class signs it with override
  3. Callers hold the interface type
  4. The real class decides what runs

The caller knows only the socket, never the plug behind it, so adding a new plug never changes the caller.

General pattern

kotlin
interface Name {
    val property: Type                       // abstract: implementers supply it
    fun required(param: Type): Result        // abstract: no body
    fun optional(): Result = defaultValue    // default body, may be overridden
}

class Implementer : Name {
    override val property: Type = value
    override fun required(param: Type): Result = value
}

A member without a body is abstract and the implementer must override it. A member with a body is a default that may be skipped or overridden. The class lists the interface after the colon, without parentheses.

Example: the Drivable contract and a Car

Drivable is the contract: it says a drive() must exist and nothing about how it works. Car fulfils the contract with override fun drive(). In this example main uses Car directly to keep things short; the later sections call the same function through the interface type.

kotlin
interface Drivable {
    fun drive()
}

class Car : Drivable {
    override fun drive() {
        println("Driving a car")
    }
}

fun main() {
    val car = Car()
    car.drive()
}

Code breakdown

  1. The contractinterface Drivable {

    The interface keyword starts a new contract. The body lists what is required, and it cannot hold state.

  2. An abstract memberfun drive()

    With no body, drive() is abstract. Every class implementing Drivable promises to provide it.

  3. Sign the contractclass Car : Drivable {

    The Drivable after the colon says Car signs this contract. Unlike extending a class, there are no parentheses after Drivable, because there is no constructor to call.

  4. Fulfil itoverride fun drive() {

    override declares that this function fulfils the interface's drive(). Remove it and you get "'drive' hides member of supertype 'Drivable' and needs an 'override' modifier"; leave the function out entirely and you get "class 'Car' is not abstract and does not implement abstract member".

  5. Use the objectcar.drive()

    Calling drive() on the Car prints "Driving a car". Declaring the variable as val car: Drivable = Car() gives the same result, because the real object decides what runs.

You should see
Driving a car
What happens when you call through the interface type
  1. The caller holds a Drivable
  2. vehicle.drive() is called
  3. Which class is the real object?

A Car

Car's drive() runs and prints Driving a car

A Bike

Bike's drive() runs and prints Pedalling a bike

Default bodies and properties in an interface

The Payable interface has three tools. currency has no getter, so it is abstract and implementers must supply it. label has a getter, so it is computed from currency with no storage. receipt() is a default body: CardPayment inherits it, while CashPayment overrides it and calls the default through super.receipt(). Notice that each implementer supplies amount() its own way; that variation is the real value of an interface.

payable.kt
interface Payable {
    val currency: String                  // abstract property
    val label: String
        get() = "payment in $currency"    // getter only: no backing field needed

    fun amount(): Int                     // abstract function

    fun receipt(): String = "$label: ${amount()}"   // default implementation
}

class CardPayment(private val cents: Int) : Payable {
    override val currency = "USD"
    override fun amount() = cents / 100
}

class CashPayment(private val kyat: Int) : Payable {
    override val currency = "MMK"
    override fun amount() = kyat
    override fun receipt() = "cash! " + super.receipt()
}

fun main() {
    val all: List<Payable> = listOf(CardPayment(2500), CashPayment(4000))
    for (p in all) println(p.receipt())
}

Several interfaces, conflicts and anonymous objects

Duck implements both Swimmer and Runner, and since both declare move() with a body, Duck must override it itself. super<Swimmer>.move() and super<Runner>.move() choose which interface's version to run. Greeter extends Named, so Student only fills in override val name and gets greet() for free. object : Greeter { ... } builds an anonymous implementation on the spot without writing a new class. And in Kotlin an interface with exactly one abstract function can be declared as a fun interface, which lets a lambda implement it.

multiple.kt
interface Swimmer {
    fun move() = println("swimming")
}

interface Runner {
    fun move() = println("running")
}

class Duck : Swimmer, Runner {
    override fun move() {
        super<Swimmer>.move()
        super<Runner>.move()
    }
}

interface Named {
    val name: String
}

interface Greeter : Named {
    fun greet() = "Hello, $name"
}

class Student(override val name: String) : Greeter

fun main() {
    Duck().move()
    println(Student("Aye").greet())
    val anon = object : Greeter {
        override val name = "anonymous"
    }
    println(anon.greet())
}

Programming against the interface type

Return to the picture from the problem. Once Car and Bike sign Drivable, a single startTrip handles both, and List<Drivable> holds the mixed vehicles. Adding a Scooter means writing one class with one override; startTrip and the for loop stay as they are.

against-interface.kt
interface Drivable {
    fun drive()
}

class Car : Drivable {
    override fun drive() {
        println("Driving a car")
    }
}

class Bike : Drivable {
    override fun drive() {
        println("Pedalling a bike")
    }
}

fun startTrip(vehicle: Drivable) = vehicle.drive()

fun main() {
    val fleet: List<Drivable> = listOf(Car(), Bike())
    for (vehicle in fleet) startTrip(vehicle)
}

In real projects

Where this shows up in real projects

In real projects an interface draws the boundary a whole feature depends on. interface UserRepository { fun find(id: Int): User? } is implemented by DatabaseUserRepository in production and by FakeUserRepository in tests. The service code knows only UserRepository, so tests run without a database and the storage can be swapped later without editing the service. This is the design rule called dependency inversion.

The standard library itself is full of interfaces. String implements Comparable<String>, which is why sorted() works on it, lists implement Iterable, which is why a for loop can walk them, and callbacks such as Runnable and Android click listeners are interfaces with a single function. In your own code, express "what it can do" as an interface and leave "how it does it" to the classes.

Common mistakes

Common mistakes

1. Leaving out a required member

With interface Drivable { fun drive() } and class Car : Drivable written without a body, the compiler reports "class 'Car' is not abstract and does not implement abstract member". That is a good error: it forces the contract to be fulfilled. A member that has a default body may be skipped.

2. Forgetting override

class Car : Drivable { fun drive() = println("x") } fails with "'drive' hides member of supertype 'Drivable' and needs an 'override' modifier". Every function that fulfils an interface member needs override.

3. Giving an interface property an initial value

interface Counter { var count: Int = 0 } fails with "property initializers in interfaces are prohibited", because an interface has no state. Leave the property abstract and let the implementer write override var count = 0.

4. Ignoring a clash between two defaults

When two interfaces both give hello() a body and you write class C : A, B, the compiler says "class 'C' must override 'hello' because it inherits multiple interface methods for it". Resolve it with an override fun hello() that calls super<A>.hello() or super<B>.hello().

Best practices

Best practices

  • Keep each interface small and about one capability; several small interfaces are easier to implement than one large one.
  • Use interface types, not concrete classes, in function signatures so that tests can pass a fake.
  • Name interfaces after the capability, such as Drivable or Comparable, rather than IVehicle, and use fun interface for single-function callbacks.

Mini challenge

Mini challenge: a Notifier contract

Write an interface for two notification channels and count how many messages each channel managed to send.

  • Notifier has an abstract channel property, an abstract send(message): Boolean and a default sendAll(messages): Int
  • EmailNotifier always succeeds and prints [email] message
  • SmsNotifier(maxLength) rejects messages longer than maxLength and prints [sms] message otherwise
  • main stores both in a List<Notifier>, sends the same two messages through each and prints how many were sent
notifier.kt
interface Notifier {
    // TODO: abstract val channel: String
    // TODO: abstract fun send(message: String): Boolean
    // TODO: default fun sendAll(messages: List<String>): Int that counts successful sends
}

// TODO: class EmailNotifier : Notifier   (always succeeds, prints "[email] ...")
// TODO: class SmsNotifier(maxLength: Int) : Notifier   (rejects long messages)

fun main() {
    // TODO: val notifiers: List<Notifier> = ...
    // TODO: send listOf("Hi", "Your parcel has arrived") through each notifier
    // TODO: print "<channel>: <sent> of 2 sent" for every notifier
}

Expected: The program prints these five lines: [email] Hi [email] Your parcel has arrived email: 2 of 2 sent [sms] Hi sms: 1 of 2 sent

Show hint

sendAll can be messages.count { send(it) }, because count counts only the items for which the lambda returns true. Declare the constructor property as private val maxLength: Int and fill channel with override val channel = "sms". The length of a message is message.length.

Show solution
notifier.kt
interface Notifier {
    val channel: String
    fun send(message: String): Boolean
    fun sendAll(messages: List<String>): Int = messages.count { send(it) }
}

class EmailNotifier : Notifier {
    override val channel = "email"
    override fun send(message: String): Boolean {
        println("[email] $message")
        return true
    }
}

class SmsNotifier(private val maxLength: Int) : Notifier {
    override val channel = "sms"
    override fun send(message: String): Boolean {
        if (message.length > maxLength) return false
        println("[sms] $message")
        return true
    }
}

fun main() {
    val notifiers: List<Notifier> = listOf(EmailNotifier(), SmsNotifier(12))
    val messages = listOf("Hi", "Your parcel has arrived")
    for (n in notifiers) {
        val sent = n.sendAll(messages)
        println("${n.channel}: $sent of ${messages.size} sent")
    }
}

Quick quiz 1 / 3

Why does interface Counter { var count: Int = 0 } not compile?

Quick quiz 2 / 3

With interface A { fun hi() = println("A") }, interface B { fun hi() = println("B") } and class C : A, B { override fun hi() { super<B>.hi(); super<A>.hi() } }, what does C().hi() print?

Quick quiz 3 / 3

Two unrelated classes must be accepted by the same function. What is the most flexible parameter type?

What to remember

  • An interface is a contract without state: a member with no body is abstract and every implementer must fill it in with override.
  • An interface may contain default function bodies and properties with getters, but a property cannot have an initial value.
  • A class may implement many interfaces, and when two defaults clash you choose with super<Type>.member().
  • Reach for an interface by default, use an abstract class when children share state, and put the interface type in your parameters.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Interfaces | Thuta Learning