Delegation with by

Kotlin language Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

interface Greeter { fun hello(): String; fun bye(): String }

class Plain : Greeter {
    override fun hello() = "hi"
    override fun bye() = "bye"
}

class Loud(inner: Greeter) : Greeter by inner {
    override fun hello() = "HI"
}

fun main() {
    val g = Loud(Plain())
    println(g.hello() + " " + g.bye())
}
Options
Hint 1 of 1

Which methods does by inner generate?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A HI bye

Correct. hello is overridden; bye is forwarded to the inner Greeter.

Why not the others?
  • B hi bye. Loud overrides hello.
  • C HI BYE. bye isn't overridden, so it's delegated.
  • D It doesn't compile: bye isn't implemented. by inner generates the missing methods.

30-second answer

Class delegation (class Logged(private val inner: Repo) : Repo by inner) generates every interface method to forward to inner, so you override only what you change. That's composition without boilerplate. Property delegation (val x by lazy { }, by mutableStateOf(), by viewModels()) hands a property's get and set to a delegate object.

Practise saying it · 30 s. No recording, just a timer

Explain delegation in Kotlin.

Say your answer out loud, then check which of these points you covered:

  • Class delegation forwards interface methods
  • Override only what changes
  • Property delegates handle get/set
  • lazy, viewModels, mutableStateOf are delegates

Deep dive

Write your own property delegate with ReadOnlyProperty / ReadWriteProperty or getValue/setValue operators.

Delegates.observable runs a callback on every change; vetoable can reject changes.

by map reads properties from a map by name.

Class delegation calls the delegate's methods, not your overrides, from inside the delegate.

Common mistakes

  • Expecting the delegate to call your override internally.
  • Writing manual forwarding methods for a large interface.
  • Hiding heavy work in a custom getter delegate.

Senior take & follow-ups

Explain both kinds and name a familiar Android delegate.

Follow-up questions

Think of your answer first, then open the hint.

  1. How does by viewModels() work?

    Show hint

    It's a property delegate that looks up or creates the ViewModel on first access.

  2. When would you use Delegates.observable?

    Show hint

    To react to changes of a simple property, like logging.

Suggest a fix if something here is wrong or out of date.