Published on

Note on Kotlin - Delegation

Authors

This article introduces you to delegation in Kotlin with real-world examples of its usage.

Theory

In object-oriented programming, delegation is a design pattern. It enables object A to use object B to provide data or perform a task. You can think about it as if object A outsources some of its work to object B.

It's common for delegation to happen via some interface between A and B instead of direct communication. Such implementation also allows the swapping of delegate objects.

Delegation pattern is not something specific to Kotlin: it's used in many other languages (the closest example could be Swift and native iOS development), so understanding its working principle helps to improve code written for other platforms as well.

Delegation is used with the by keyword.

Outsourcing part of the implementation to delegate object makes it much more flexible and reusable.

Example

Below is a general use case of delegation pattern:

// Defining the interface with one method.
interface Job {
    fun attack()
}

// Writing class which implements Job interface by
// overriding the method.
class JobImpl(val name: String): Job {
    override fun attack() {
        println("$name attacks")
    }
}

// Creating another class which implements the interface
// Job by delegating it to a particular object.
class Player(val job: JobImpl) : Job by job

// The result: Player supports "attack" method 🎉
fun main() {
    val player = Player(JobImpl("Arcanist"))
    player.attack()
}

Conclusion

There are other areas where delegation pattern could be used, such as events handling, view models, and more. If you want to learn more about it, check out the Resources section.

Have fun 👩‍💻

Resources

  1. Kotlin Programming Language Official Website - https://kotlinlang.org/
  2. Kotlin Delegation - https://kotlinlang.org/docs/reference/delegation.html
  3. Delegation pattern - https://en.wikipedia.org/wiki/Delegation_pattern