Skip to main content

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

  1. Live Demo
  2. interface Base {
  3. fun printMe() //abstract method
  4. }
  5. class BaseImpl(val x: Int) : Base {
  6. override fun printMe() { println(x) } //implementation of the method
  7. }
  8. class Derived(b: Base) : Base by b // delegating the public method on the object b
  9. fun main(args: Array<String>) {
  10. val b = BaseImpl(10)
  11. Derived(b).printMe() // prints 10 :: accessing the printMe() method
  12. }

Output
10

Comments

Popular posts from this blog

Jetpack Compose based Android interview and questions

Null safety based Kotlin interview questions and answers

CustomView based Android interview questions and answers