Junior — Middle
Kas saaksite selgitada delegatsiooni kontseptsiooni Kotlinis ja selle kasutamist?
sobes.tech AI
Vastus AI-lt
In Kotlin, delegation is a mechanism that allows the transfer of the implementation of a specific interface or property to another object, instead of implementing it directly in the class.
Main types of delegation:
- Interface delegation — the 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() // Prints 10
}
- Property delegation — allows overriding the behavior of getters and setters using special delegates like
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.