Sobes.tech
Middle

What is delegation in Kotlin?

sobes.tech AI

Answer from AI

Delegation in Kotlin is a design pattern where an object (the delegate) takes responsibility for executing a specific task on behalf of another object. Kotlin supports native delegation at the syntax level.

There are two main types of delegation in Kotlin:

  1. Class Delegation: Allows a class A to implement an interface by delegating all method calls to another object B.

    interface Base {
        fun printMessage()
    }
    
    class BaseImpl(val x: Int) : Base {
        override fun printMessage() {
            println(x)
        }
    }
    
    class Derived(b: Base) : Base by b // Delegation to object b
    

    In the example, Derived delegates the implementation of Base to object b.

  2. Delegated Properties: Allows delegating the logic of getting and setting a property to another object. Kotlin provides several standard delegates:

    • lazy() for lazy initialization.
      val lazyValue: String by lazy {
          println("computing!")
          "Hello"
      }
      
    • Delegates.observable() for change notification.
      import kotlin.properties.Delegates
      
      var name: String by Delegates.observable("initial value") {
          prop, old, new ->
          println("$old -> $new")
      }
      
    • Delegates.vetoable() for intercepting changes.
      import kotlin.properties.Delegates
      
      var max: Int by Delegates.vetoable(0) {
          prop, old, new -> new > old
      }
      
    • Delegates for binding to map properties.
      class User(val map: Map<String, Any?>) {
          val name: String by map
          val age: Int by map
      }
      
      Usage: User(mapOf("name" to "John Doe", "age" to 25))

Advantages of delegation in Kotlin:

  • Reduction of boilerplate: automatic forwarding of method calls or property logic.
  • Code reuse: ability to use existing delegates or create custom ones.
  • Separation of concerns: clear division of property or interface logic.
  • Flexibility: change delegation behavior without modifying the class.
What is delegation in Kotlin? — Android - sobes.tech