What does 'by' keyword do in Kotlin?


Kotlin supports delegation of design pattern by introducing a new keyword "by". Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.

Example

In this example, we will implement an abstract method of a Base class from another class.

interface Base {
   //abstract method
   fun printMe()
}

class BaseImpl(val x: Int) : Base {
   // implementation of the method
   override fun printMe() { println(x) }
}

// delegating the public method on the object b
class Derived(b: Base) : Base by b

fun main(args: Array<String>) {
   val b = BaseImpl(10)

   // prints 10 :: accessing the printMe() method
   Derived(b).printMe()
}

Output

It will produce the following output

10

Updated on: 23-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements