Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 134 ยท Classes and Objects

Interfaces

Learn Kotlin interfaces: abstract members, default implementations, properties, implementing several interfaces, resolving conflicts with super, fun interfaces and when to prefer them.

An interface describes what an object can do without saying how. A Comparable can be compared, a Closeable can be closed, a Shape can compute its area. Code that depends on an interface works with every class that implements it, today and in the future. That is the main tool for writing flexible, testable programs: you depend on a small contract rather than on a concrete class.

Kotlin interfaces are more capable than the ones in old Java: they may contain default implementations and properties, but they can never hold state (no stored fields). In this lesson you declare and implement interfaces, give members default bodies, combine several interfaces and resolve name clashes, and meet fun interfaces, which let a lambda stand in for a one-method interface.

Declaring and implementing an interface

Kotlin A first interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is circle: 3.14 and square: 9.00. report knows only Shape; it works with any class that promises area() and name(). A class lists interfaces after the colon, without parentheses (an interface has no constructor to call), and must override every abstract member. Members of an interface are public and open; you cannot make them private unless they have a body.

If you forget one, the compiler tells you:

Kotlin A missing implementation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error reads main.kt:6:1: error: class 'Triangle' is not abstract and does not implement abstract member: followed by fun name(): String. Either implement name() or declare Triangle as abstract (see Abstract Classes).

Default implementations

A member with a body is a default implementation: implementing classes get it for free and may override it. This is how interfaces grow without breaking existing implementers:

Kotlin Default methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Output: Hello, Ana!, HELLO, ANA! and BEEP. I AM R2.. Robot overrides only greeting(), and shout() calls the overridden version. Notice the pattern: a few abstract members (name) and many default members built on top of them. The standard library's Comparable-style interfaces and Kotlin's Iterable follow it.

Properties in interfaces

An interface can declare properties, but it cannot store them: there is no backing field. A property is either abstract (the implementer provides it) or has a getter:

Kotlin Abstract and computed properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Printed: S1: 10.50, S1+S2: 13.25, S1+S2: 14.25. Savings overrides the read-only val balanceCents with a var, which is allowed: an implementer may be more capable than the interface demands. Joint computes its balance with a getter and so stores nothing.

Implementing several interfaces

A class can have only one superclass but any number of interfaces. When two interfaces provide the same default member, the class must say which one it wants (or write its own) using super<Interface>:

Kotlin Resolving a conflict with super

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both calls print walking and swimming, because Duck supplies the one implementation both interfaces see; the call through the Walker variable still runs Duck's override. If Duck did not override move, the compiler would stop with error: class 'Duck' must override 'move' because it inherits multiple interface methods for it.

Interfaces versus abstract classes

Both can declare abstract members and provide default bodies. The differences decide which to use:

Interface Abstract class
Stored state (fields) no yes
Constructor no yes
How many a class can use many exactly one superclass
Typical purpose a capability or role a partial implementation with shared state

Start with an interface. Reach for an abstract class when subclasses really share fields and initialization code. And because a class can implement many interfaces, it can play many roles: class User : Comparable<User>, Serializable.

Anonymous implementations with object expressions

You do not need a named class to implement an interface once. An object expression creates an anonymous object on the spot, useful for small callbacks, tests and fakes:

Kotlin An object expression implementing an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The two lines are [09:00] started and [17:30] stopped. Fakes like this keep clocks, random numbers and network calls out of your logic so that it can be tested (see Test Doubles). More on object expressions in Objects and Companion Objects.

fun interfaces

An interface with exactly one abstract method is a candidate for a fun interface. Writing fun interface allows callers to supply the implementation as a lambda (this is called SAM conversion, from "single abstract method"):

Kotlin A fun interface with lambdas

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The four lines are ok: hello, rejected: (with the three spaces), rejected: kotlin! and ok: tree. The last call passes a bare lambda where a Validator is expected: the compiler converts it. A normal interface would require object : Validator { ... } every time.

When do you need a fun interface instead of a function type like (String) -> Boolean? Mostly for Java interop (Java callers see a real interface), when you want a named type with documentation, or when you want to add extra members with defaults later. For purely Kotlin code, a function type or a typealias is often shorter. Fun interfaces may have default members, but only one abstract one.

A fun interface may contain exactly one abstract member. Adding a second abstract function makes the fun modifier an error, because lambdas could no longer implement it.

Design notes

  • Name by role. Repository, Clock, Shape, Comparator. Avoid the IFoo prefix and FooImpl suffix when a better name exists.
  • Keep interfaces small. Several focused interfaces beat one large one; implementers then only promise what they can deliver.
  • Do not expose mutable state through defaults. An interface cannot hold fields, so a default that tries to "remember" something is a sign you need an abstract class.
  • Delegation reduces boilerplate: class Logged(inner: Shape) : Shape by inner forwards every member to inner and lets you override just the ones you want (see Delegation).
  • Sealed interfaces (see Sealed Classes and Interfaces) restrict who can implement them, so a when can be exhaustive.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does a class list an interface it implements?

    Interfaces have no constructor, so no parentheses. A superclass is written with a constructor call; an interface is not.
  2. 2. What can an interface NOT have?

    Interfaces hold no state. Properties must be abstract or computed by a getter.
  3. 3. Two interfaces both provide fun move() with a body, and a class implements both. What must the class do?

    The compiler refuses to guess; the class has to provide its own override, and super<Type> selects which default to call.
  4. 4. What does fun interface allow?

    SAM conversion lets a lambda be passed where the fun interface is expected, or be turned into one with Name { ... }.
  5. 5. When is an abstract class a better fit than an interface?

    Only abstract classes hold state and have constructors. Interfaces can offer defaults, so that alone is not the deciding factor.

Summary

  • An interface declares members that implementers promise to provide; list it after the colon without parentheses.
  • Members can have default bodies, and properties may be abstract or computed, but an interface stores no state.
  • A class may implement many interfaces; resolve clashing defaults by overriding and calling super<Name>.member().
  • Object expressions create one-off implementations; fun interface allows lambdas for single-method interfaces.
  • Prefer interfaces for roles and abstract classes for shared state.

Next: Abstract Classes