1. Overview
In this article, we will discuss about Interface or class delegation using “by” keyword in Kotlin.
2. Interface or Class Delegation
Delegation pattern is an object-oriented design pattern proven to be a suitable alternative to implementation inheritance and requires zero boilerplate code. It allows you to write the reusable code once and for all. Delegation means passing the responsibility to another class or method.
Let’s see an example without delegation.
class BaseImpl(val x: Int) { override fun print() { print(x) } } class Derived(b: Base) { fun print() { b.print() } } fun main() { val b = BaseImpl(10) Derived(b).print() }
In this example, BaseImpl class has print() function. Suppose you also need the same print() function inside your other class Derived. To avoid writing the same code again, you are passing the instance of BaseImpl to your Derived class and calling the print() function wherever required inside your Derived class. In short, the class Derived delegates the print() call to the delegate class BaseImpl instead of rewriting the code.
In Kotlin, the same delegation can be achieved using the by keyword with zero boilerplate code.
interface Base { fun print() } class BaseImpl(val x: Int) : Base { override fun print() { print(x) } } class Derived(b: Base) : Base by b fun main() { val b = BaseImpl(10) Derived(b).print() }
Let’s declare an interface Base with the print() function. Write a BaseImpl class that provides the public implementation of all the interface functions once and for all. The by keyword in the class definition shows that the Derived class holds the object b.
The Derived class doesn’t implement any interface methods and instead it delegates all the public method calls of the interface to object b. When you call print() on the Derived object, the call goes to delegate object b (BaseImpl)
3. Conclusion
In this article, we have seen the by keyword and all its use cases in Kotlin