DEV Community

Sanjay Prajapat
Sanjay Prajapat

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

1 1

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more