Junior — Middle
Can you explain the concept of delegation in Kotlin and its application?
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. This helps avoid code duplication and simplifies composition.
The most common example is property delegation using the by keyword.
Example of property delegation:
class User {
var name: String by Delegates.observable("") { prop, old, new ->
println("Property ${prop.name} changed from $old to $new")
}
}
You can also delegate the implementation of an interface:
interface Printer {
fun print()
}
class RealPrinter : Printer {
override fun print() {
println("Printing document")
}
}
class Manager(printer: Printer) : Printer by printer
fun main() {
val realPrinter = RealPrinter()
val manager = Manager(realPrinter)
manager.print() // call is delegated to realPrinter
}
This approach allows for responsibility separation and code reuse without inheritance.