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:
-
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 bIn the example,
Deriveddelegates the implementation ofBaseto objectb. -
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.
Usage:class User(val map: Map<String, Any?>) { val name: String by map val age: Int by map }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.