2
2
.
.
4
4
.
.
7
7
D
D
e
e
l
l
e
e
g
g
a
a
t
t
i
i
o
o
n
n
I
I
n
n
f
f
o
o
[
[
R
R
]
]
Class that Implements Interface doesn't need to override Interface's Methods.
Instead it can Delegate this job to an Object which already has these Implementations.
This way you can avoid re-implementing the same Interface that you have already Implemented elsewhere.
As a Delegate you specify an Object (rather than a Class). Since Kotlin can also have Classless Objects which can also
implement Interface this way you can delegate either to an Instance of a Class or a standalone Object.
Interface Delegation
//INTERFACE: InterfaceA
interface InterfaceA {
abstract fun abstractMethod();
}
//CLASS: Person
class Person : InterfaceA {
override fun abstractMethod() { println("Overriden abstractMethod()" ); }
}
//CLASS: Soldier
class Soldier(var person: Person) : InterfaceA by person { }
//===========================================================================================================
//FUNCTION: main
//===========================================================================================================
fun main() {
var person = Person()
var soldier = Soldier(person) //We will use this Objet's Interface Implementation
soldier.abstractMethod() //Using Implementation from Person Class
}