Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 134 ยท Classes and Objects

Delegation

Learn Kotlin delegation: implement interfaces with by, build decorators, use lazy, observable and vetoable properties, store properties in a map and write your own delegate.

Inheritance is the textbook way to reuse behavior, but it ties a class to one parent for life and exposes everything the parent does. Experienced designers often prefer composition: a class holds another object and hands work to it. The catch is boilerplate. If an interface has twelve methods and you want to change one, you must write eleven forwarding methods by hand.

Kotlin removes that boilerplate with the keyword by. It gives you two related tools. Class delegation lets a class implement an interface by forwarding every member to another object. Property delegation lets a property hand its reading and writing to a helper object, which is how lazy, observable properties and map-backed properties work. This lesson covers both, plus how to write your own delegate. It builds on Interfaces, Inheritance and Classes and Properties.

Class delegation: implementing an interface with by

Imagine a small Logger interface. A PrefixLogger should behave like any logger but add a prefix. Here is the delegation version:

Kotlin Implementing an interface by delegating

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 clause : Logger by inner tells the compiler: "generate every member of Logger in this class as a call on inner". You then override only what you want to change. The result is the decorator pattern in a few lines. Notice that PrefixLogger is not a subclass of ConsoleLogger; it can wrap any Logger, and you can stack several wrappers.

The delegate is evaluated once, when the object is constructed, and stored in a hidden field. Class delegation works for interfaces only, never for classes. If Logger gains a method later, PrefixLogger keeps compiling and forwards it, which is a real advantage over hand-written forwarding.

A trap: the delegate does not know about the wrapper

With inheritance, a parent method that calls another overridable method reaches your override. With delegation it does not, because the delegate is a separate object that has no idea it is being wrapped. Counting how often elements are added shows the difference:

Kotlin Delegation is not inheritance

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 list holds five elements, but only two add calls were counted: addAll goes straight to the inner list, which does its own work without calling your add. If you subclassed ArrayList and overrode add, the result depends on how addAll is implemented inside the parent, a famous fragility. With delegation the behavior is at least predictable: only the members you override are intercepted. To count everything you would override addAll too.

Property delegation

A property can say: "do not store my value yourself; ask this other object". The syntax is val name: Type by delegate. The delegate is any object with a getValue function (and setValue for a var) with the right signature. The standard library ships useful ones.

lazy: compute on first use

Kotlin lazy runs its block once

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.

lazy takes a lambda, runs it the first time the property is read, remembers the result and returns it ever after. The block is a good place for work that is expensive and may never be needed. By default lazy is thread safe: if two threads read the property at the same moment, only one runs the block. If you know there is only one thread you can pass LazyThreadSafetyMode.NONE to avoid the locking cost. A lazy property must be a val, because the value is computed once.

If the block throws, nothing is cached and the next read tries again.

Delegates.observable and vetoable

Delegates.observable calls your lambda after every assignment, giving you the property, the old value and the new one. Delegates.vetoable calls it before assignment and lets you refuse the change by returning false:

Kotlin Observing and vetoing changes

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 number in parentheses is the initial value. The first lambda parameter (the property reference) is unused here, so it is written _. These two delegates are handy for validation and for small reactive updates; for anything beyond that, consider a StateFlow (see StateFlow and SharedFlow).

Properties stored in a map

A map can back a class's properties. Each property reads the entry whose key equals the property name. This is popular when parsing loosely structured data such as JSON or configuration:

Kotlin Map-backed 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.

The map is the single source of truth. With a MutableMap, a var property writes through into the map. The compiler cannot check that the keys exist or have the right types, so mistakes surface at run time:

Kotlin A missing key fails at read time (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 first line prints localhost, then the program crashes with Exception in thread "main" java.util.NoSuchElementException: Key port is missing in the map. and a stack trace. Notice that construction succeeded: the failure comes only when the property is read. For that reason, validate the map once up front if the data is untrusted.

Writing your own delegate

A delegate is just an object with operator functions. The easiest way is to implement ReadWriteProperty<Any?, T> (or ReadOnlyProperty for a val), which forces the correct signatures:

Kotlin A delegate that trims and counts writes

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.

For every access the compiler calls getValue(thisRef, property): thisRef is the object that owns the property (Person here, shown as Any? because this delegate works anywhere) and property carries metadata such as the name. ReadWriteProperty is declared in the standard library, so you do not need extra dependencies. The helper property.name works without the full reflection library; this is one of the things the Kotlin runtime provides by itself.

You can also create a delegate that is reusable across properties by writing a function that returns one:

Kotlin A delegate factory function

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.

ReadOnlyProperty is a fun interface, so a lambda can create one directly. Each property gets its own copy of calls, because counted(...) is called once per property declaration.

Delegating to another property

A property can also forward to another property with by ::other, which is useful for deprecation (the old name keeps working) and for aliases. The target must be accessible and have a compatible type:

Kotlin
class Account(var balance: Int) {
    var funds: Int by this::balance   // alias; both names read and write the same value
}

Choosing between inheritance and delegation

  • Use class delegation when you want to reuse an interface implementation, decorate it, or combine several behaviors without a parent class.
  • Use inheritance when there is a true "is a" relationship with shared state, and the parent is designed for extension (marked open with documented hooks).
  • Use property delegation to share a pattern of accessing properties, such as lazy init, validation or storage, rather than copy the same getter and setter code.

Performance note: each delegated property adds a hidden delegate object and, for lazy, a few extra bytes and a synchronization check. In a class instantiated millions of times, a plain by lazy on rarely-used properties can still save memory and time, but a plain field is cheaper if the value is always needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does class A(private val b: Base) : Base by b do?

    The compiler generates every Base member in A as a call on b; you override only the members you want to change. Delegation works for interfaces, not classes.
  2. 2. How many times does the block of val x: Int by lazy { println("calc"); 5 } run when x is read three times (single thread)?

    lazy runs the block on the first read and caches the result for all later reads.
  3. 3. What is the difference between Delegates.observable and Delegates.vetoable?

    observable reports a change that already happened. vetoable can reject a new value by returning false, in which case the old value is kept.
  4. 4. In class C(m: Map<String, Any?>) { val port: Int by m }, when is a missing "port" key detected?

    The map is consulted on every read, so a missing key throws NoSuchElementException only when the property is accessed.
  5. 5. Why did CountingList count only two add() calls after two add and one addAll call?

    A delegate is an independent object. Calls made inside it never come back to the wrapper's overrides, unlike inheritance, where this is the subclass.

Summary

  • class A : Interface by obj implements an interface by forwarding all members to obj; override members to change them.
  • Delegates are separate objects: their internal calls never reach the wrapper's overrides.
  • val x by lazy { ... } computes a value on first read (thread safe by default) and caches it.
  • Delegates.observable reacts after each assignment, Delegates.vetoable can reject a change.
  • by map reads (and for var, writes) properties from a map by property name; missing keys fail at read time.
  • A custom delegate implements getValue (and setValue), easiest via ReadWriteProperty or ReadOnlyProperty.
  • Prefer composition and delegation to deep inheritance when you only want to reuse behavior.

Next: Advanced Properties