AnyCompiler

Interfaces

An interface defines a set of functions a class must implement. Unlike a class, a class can implement multiple interfaces at once, and completely unrelated classes — Circle and Square here share nothing but Shape — can all satisfy the same interface. Note that, unlike classes, interface member functions don't need the open keyword — they're implicitly overridable by design.

interface Shape {
    fun area(): Double
}

class Circle(val radius: Double) : Shape {
    override fun area() = Math.PI * radius * radius
}

class Square(val side: Double) : Shape {
    override fun area() = side * side
}

fun main() {
    val shapes = listOf(Circle(2.0), Square(3.0))
    for (s in shapes) {
        println(s.area())
    }
}
Output
12.566370614359172
9.0

Next: sealed classes — a restricted class hierarchy the compiler can check exhaustively, with no equivalent in Java, C++, or C# on this site.

Practice exercise

Define an interface Named with a fun getName(). Define a class Dog implementing Named with a private name field. Write a fun greet(n: Named) that prints "Hello, " followed by n.getName(). Call it with a Dog named "Rex".