DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Updated on • Originally published at sanjayprajapat.hashnode.dev

Delegation In Kotlin

kotlin support delegation pattern using by keyword. it allows the derived class to access all the implemented public methods of an interface through a specific object.

interface Base {
    fun print()
}
Enter fullscreen mode Exit fullscreen mode
class BaseImpl(val x:String):Base{
   override val msg: String?  = x  
    override fun print(){
        println("Printing impl ${msg}}")
    }
}
class BaseAnotherImpl():Base{
     override val msg: String?  = null  
    override fun print(){
        println("Printing Another impl ")
    }
}
Enter fullscreen mode Exit fullscreen mode

don't need to write this code

//class Derived (val b:Base) :Base{
//     override fun print(){
//         b.print()  // delegating the responsibility  of b reference
//     }
// }

Enter fullscreen mode Exit fullscreen mode

kotlin supports this natively use this code

class Derived(b:Base):Base by b 
Enter fullscreen mode Exit fullscreen mode
fun main(args: Array<String>) {
    val b1 = BaseImpl("Hell")
    Derived(b1).print()

    val b2 = BaseAnotherImpl() // Printing impl Hell
    Derived(b2).print() // Printing Another impl    
}
Enter fullscreen mode Exit fullscreen mode

Overriding member of an interface implemented by delegation

class Derived(b:Base):Base by b  {
    override val msg  = "2"   // can't access this property by b reference 

    override fun print(){
        print("\noverriding  print method of interface ")

    }
}
Enter fullscreen mode Exit fullscreen mode
  // after overiding 
    val d = Derived(b1)
    d.print() // overriding  print method of interface
    print(d.msg) // 2 

Enter fullscreen mode Exit fullscreen mode

Original post on sanjayprajapat.hashnode.dev

Top comments (0)