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()
}
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 ")
}
}
don't need to write this code
//class Derived (val b:Base) :Base{
// override fun print(){
// b.print() // delegating the responsibility of b reference
// }
// }
kotlin supports this natively use this code
class Derived(b:Base):Base by b
fun main(args: Array<String>) {
val b1 = BaseImpl("Hell")
Derived(b1).print()
val b2 = BaseAnotherImpl() // Printing impl Hell
Derived(b2).print() // Printing Another impl
}
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 ")
}
}
// after overiding
val d = Derived(b1)
d.print() // overriding print method of interface
print(d.msg) // 2
Original post on sanjayprajapat.hashnode.dev
Top comments (0)