Delegation based Kotlin interview questions and answers
What is Kotlin delegation?
Kotlin supports the “delegation” design pattern by introducing a new keyword “by”. Using the keyword or delegation methodology. Kotlin allows the derived class to access all of the implemented public methods of an interface through a specific object.
Example
- Live Demo
 - interface Base {
 - fun printMe() //abstract method
 - }
 - class BaseImpl(val x: Int) : Base {
 - override fun printMe() { println(x) } //implementation of the method
 - }
 - class Derived(b: Base) : Base by b // delegating the public method on the object b
 - fun main(args: Array<String>) {
 - val b = BaseImpl(10)
 - Derived(b).printMe() // prints 10 :: accessing the printMe() method
 - }
 
Output
10
Comments
Post a Comment