Sobes.tech
Junior — Middle

Can you explain the concept of delegation in Kotlin and its usage?

sobes.tech AI

Answer from AI

In Kotlin, delegation is a mechanism that allows passing the implementation of a specific interface or property to another object, instead of implementing it directly in the class.

Main types of delegation:

  1. Interface delegation — a class implements an interface but actually calls methods of another object:
interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { println(x) }
}

class Derived(b: Base) : Base by b

fun main() {
    val b = BaseImpl(10)
    Derived(b).print()  // Outputs 10
}
  1. Property delegation — allows overriding the behavior of getters and setters through special delegates, such as lazy, observable, or custom ones:
val lazyValue: String by lazy {
    println("Calculating value")
    "Hello"
}

Using delegation helps reduce code duplication, increase flexibility, and promote component reuse.