Kotlin Academy · Lesson

The by Keyword

Delegate interface implementation.

Lesson 1 of 413 steps

The by Keyword is a free Kotlin Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

What Is Delegation?

Class delegation lets one object hand off an interface's implementation to another object. Kotlin builds this into the language with the by keyword.

It is composition made effortless.

An Interface to Delegate

Start with an interface and a concrete implementation. We will later delegate to this implementation.

interface Speaker {
    fun speak(): String
}

class LoudSpeaker : Speaker {
    override fun speak() = "HELLO!"
}

fun main() {
    println(LoudSpeaker().speak())
}

The by Keyword

Write class X(d: Iface) : Iface by d. The compiler generates forwarding methods that call d for every interface member.

interface Speaker {
    fun speak(): String
}

class LoudSpeaker : Speaker {
    override fun speak() = "HELLO!"
}

class Announcer(s: Speaker) : Speaker by s

fun main() {
    val a = Announcer(LoudSpeaker())
    println(a.speak())
}

No Boilerplate

Without by you would write a forwarding method for every interface function by hand. Delegation generates all of them automatically.

interface Repository {
    fun save(item: String): String
    fun count(): Int
}

class MemoryRepo : Repository {
    private val items = mutableListOf<String>()
    override fun save(item: String): String { items.add(item); return item }
    override fun count() = items.size
}

class LoggingRepo(r: Repository) : Repository by r

fun main() {
    val repo = LoggingRepo(MemoryRepo())
    repo.save("a")
    println(repo.count())
}

Overriding Selected Members

You can override just the members you want to customize; the rest are still forwarded to the delegate.

interface Repository {
    fun save(item: String): String
    fun count(): Int
}

class MemoryRepo : Repository {
    private val items = mutableListOf<String>()
    override fun save(item: String): String { items.add(item); return item }
    override fun count() = items.size
}

class LoggingRepo(private val r: Repository) : Repository by r {
    override fun save(item: String): String {
        println("saving " + item)
        return r.save(item)
    }
}

fun main() {
    val repo = LoggingRepo(MemoryRepo())
    repo.save("book")
    println(repo.count())
}

Delegate as a Parameter

The delegate is usually passed via the primary constructor. You can keep a reference with private val if you also override some members.

interface Clock { fun now(): Int }

class FixedClock : Clock { override fun now() = 12 }

class App(private val clock: Clock) : Clock by clock

fun main() {
    println(App(FixedClock()).now())
}

Delegating Standard Interfaces

You can delegate to built-in collection interfaces, instantly getting a wrapper that behaves like the underlying collection.

class TaggedList(private val inner: List<String>) : List<String> by inner {
    val tag = "v1"
}

fun main() {
    val tl = TaggedList(listOf("x", "y"))
    println(tl.size)
    println(tl[0])
    println(tl.tag)
}

How It Compiles

Behind the scenes, the compiler stores the delegate and emits forwarding implementations. The generated methods simply call the delegate's matching method. It is the same as hand-written forwarding, minus the typing.

A Captured Snapshot

Important subtlety: the delegate reference is captured when the object is built. Overridden members call the delegate explicitly, but generated forwarders use the originally supplied instance.

interface Source { fun value(): Int }

class Const(val n: Int) : Source { override fun value() = n }

class Wrapper(s: Source) : Source by s

fun main() {
    val w = Wrapper(Const(42))
    println(w.value())
}

Why Use by

The by keyword lets you:

  • Reuse existing implementations
  • Add behavior without subclassing
  • Avoid fragile inheritance hierarchies

It is Kotlin's first-class support for the composition-over-inheritance principle.

The Foundation

This by keyword is the foundation for everything in this course. Next we look more closely at delegating to member objects to compose behavior.

Quick Check

Test your understanding of the by keyword.

Recap

You learned class delegation with by:

  • Delegate an interface to another object
  • Auto-generated forwarding methods
  • Override selected members while forwarding the rest
  • Works with built-in interfaces too

Next: delegating to members to compose behavior.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “The by Keyword” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “The by Keyword”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “The by Keyword”?

Delegate interface implementation. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “The by Keyword” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The by Keyword
  2. Delegating to Members
  3. Delegation vs Inheritance
  4. Practical Patterns
← Back to Kotlin Academy