HomeAndroidWhat's Delegation Interface in Kotlin?

What’s Delegation Interface in Kotlin?


You might be accustomed to delegated properties in Kotlin, however have you ever heard of delegation interface? This is without doubt one of the options different programming languages do NOT have.

Commonplace Interface Implementation

To illustrate you will have 2 interfaces under – Interface1 and Interface2.

interface Interface1 {
    enjoyable fun1()
}

interface Interface2 {
    enjoyable fun2()
}

You’ve a Class that implements these 2 interfaces. So it overrides the fun1() and fun2() from these 2 interfaces.

class Class : Interface1, Interface2{
    override enjoyable fun1() {
        println("fun1")
    }

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

In brief, the category diagram seems like this.

delegation_interface_1.drawio.png

The caller utilization seems like this.

enjoyable essential() {
    val obj = Class()
    obj.fun1()
    obj.fun2()
}

There may be nothing fancy right here, it’s a fairly normal interface implementation.

Delegation Interface Implementation

One other approach to implement this normal interface above is utilizing the delegation interface. Let us take a look at the delegation interface implementation class diagram under.

delegation_interface_2.drawio.png

The Class has now not implementing fun1() and fun2(). It delegates the implementations to situations of Interface1Impl and Interface2Impl.

The code seems like this now.

interface Interface1 {  
    enjoyable fun1()  
}  

interface Interface2 {  
    enjoyable fun2()  
}  

class Interface1Impl: Interface1 {  
    override enjoyable fun1() {  
        println("fun1")  
    }  
}  

class Interface2Impl: Interface2 {  
    override enjoyable fun2() {  
        println("fun2")  
    }  
}  

class Class : Interface1 by Interface1Imp(), Interface2 by Interface2Imp() {  

}

As you may see, fun1() and fun2() implementations in Class have been moved out to Interface1Impl and Interface2Impl. The good thing about doing that is making the Class much less litter, not bloated with completely different sort of interface implementations.

Please observe the Interface1Imp() and Interface2Imp() are the situations of the category.

You too can override the delegation interface. Interface1Impl.fun1() is overridden by Class.fun1() under.

class Class : Interface1 by Interface1Imp(), Interface2 by Interface2Imp() {  
    override enjoyable fun1() {  
        println("override fun1")  
    }  
}

Abstract

Effectively, it looks like the delegation interface is only a sugar syntax. I have never personally used it but. I have no idea whether or not I’ll finally use it. It seems prefer it may very well be a superb choice to interchange inheritance.

For sensible utilization, possibly you can too watch this video from Phillip Lackner.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments