What’s Delegation Interface in Kotlin?

You’ll be accustomed to delegated houses in Kotlin, however have you ever heard of delegation interface? This is likely one of the options different programming languages do NOT have.

Same old Interface Implementation

Let’s assume you may have 2 interfaces beneath – Interface1 and Interface2.

interface Interface1 {
    amusing fun1()
}

interface Interface2 {
    amusing fun2()
}

You will have a Magnificence that implements those 2 interfaces. So it overrides the fun1() and fun2() from those 2 interfaces.

elegance Magnificence : Interface1, Interface2{
    override amusing fun1() {
        println("fun1")
    }

    override amusing fun2() {
        println("fun2")
    }
}

Briefly, the category diagram looks as if this.

delegation_interface_1.drawio.png

The caller utilization looks as if this.

amusing primary() {
    val obj = Magnificence()
    obj.fun1()
    obj.fun2()
}

There’s not anything fancy right here, this is a beautiful usual interface implementation.

Delegation Interface Implementation

In a different way to enforce this usual interface above is the usage of the delegation interface. Let us take a look at the delegation interface implementation elegance diagram beneath.

delegation_interface_2.drawio.png

The Magnificence has not imposing fun1() and fun2(). It delegates the implementations to circumstances of Interface1Impl and Interface2Impl.

The code looks as if this now.

interface Interface1 {  
    amusing fun1()  
}  

interface Interface2 {  
    amusing fun2()  
}  

elegance Interface1Impl: Interface1 {  
    override amusing fun1() {  
        println("fun1")  
    }  
}  

elegance Interface2Impl: Interface2 {  
    override amusing fun2() {  
        println("fun2")  
    }  
}  

elegance Magnificence : Interface1 by way of Interface1Imp(), Interface2 by way of Interface2Imp() {  

}

As you’ll be able to see, fun1() and fun2() implementations in Magnificence were moved out to Interface1Impl and Interface2Impl. The advantage of doing that is making the Magnificence much less litter, now not bloated with other roughly interface implementations.

Please be aware the Interface1Imp() and Interface2Imp() are the circumstances of the category.

You’ll be able to additionally override the delegation interface. Interface1Impl.fun1() is overridden by way of Magnificence.fun1() beneath.

elegance Magnificence : Interface1 by way of Interface1Imp(), Interface2 by way of Interface2Imp() {  
    override amusing fun1() {  
        println("override fun1")  
    }  
}

Abstract

Smartly, it kind of feels just like the delegation interface is only a sugar syntax. I have not for my part used it but. I have no idea whether or not I’ll in the end use it. It appears love it generally is a just right method to exchange inheritance.

For sensible utilization, perhaps you’ll be able to additionally watch this video from Phillip Lackner.

Leave a Reply