Junior — Middle
What types of delegates for interfaces do you know and apply in practice?
sobes.tech AI
Answer from AI
In Android development, the following types of delegates are often used for implementing interface delegation:
-
Anonymous classes — a classic way where the interface is implemented directly at the usage site. Convenient for one-time handlers.
-
Lambda expressions (starting from Java 8 and in Kotlin) — a more compact and readable way to implement interfaces with a single method (functional interfaces).
-
Classic delegates in Kotlin — using the
bykeyword to delegate the implementation of an interface to another object, simplifying code and increasing reusability.
Example of interface delegation in Kotlin:
interface ClickListener {
fun onClick()
}
class ButtonClickHandler : ClickListener {
override fun onClick() {
println("Button clicked")
}
}
class MyActivity(clickListener: ClickListener) : ClickListener by clickListener {
// MyActivity delegates the implementation of ClickListener to the clickListener object
}
fun main() {
val handler = ButtonClickHandler()
val activity = MyActivity(handler)
activity.onClick() // Will print: Button clicked
}
This approach helps to separate responsibilities and simplifies code maintenance.