Delegation in Kotlin: A Beginner’s Guide to Code Modularity and Reusability

Alex Manhooei
2 min readJan 3, 2023

--

Delegation is a programming technique that allows one object or class to delegate some of its responsibilities to another object or class. In Kotlin, you can use delegation to create reusable and modular code, and to avoid inheritance hierarchies.

To use delegation in Kotlin, you can use the by keyword to specify a delegate object. For example, consider the following interface and class:

interface Base {
fun foo()
}

class Derived(b: Base) : Base by b

The Base interface defines a single method, foo, and the Derived class implements Base by delegating to an instance of Base. This means that the Derived class does not have to implement the foo method itself; it can simply delegate the call to the delegate object.

Here is an example of how you might use the Derived class:

fun main() {
val base = object : Base {
override fun foo() {
println("foo called on base object")
}
}

val derived = Derived(base)
derived.foo()
}

In this example, the main function creates an instance of the Base interface and passes it to the constructor of Derived. When the foo method is called on the derived object, it is delegated to the base object, which prints "foo called on base object" to the console.

You can also use delegation to create classes that have multiple behaviors or interfaces. For example, consider the following interface and class:

interface Base1 {
fun foo()
}

interface Base2 {
fun bar()
}

class Derived(b1: Base1, b2: Base2) : Base1 by b1, Base2 by b2

The Derived class implements both the Base1 and Base2 interfaces by delegating to separate delegate objects. This allows the Derived class to have multiple behaviors or interfaces, without having to implement them itself.

Overall, delegation is a powerful technique in Kotlin that allows you to create reusable and modular code, and to avoid inheritance hierarchies. It is a useful tool for organizing and extending your codebase in a flexible and scalable way.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Alex Manhooei
Alex Manhooei

Written by Alex Manhooei

Staff Software Engineer @ Google. All of my blog posts are my personal opinions and not related to my work at google in any shape or form.

No responses yet

Write a response