What does 'by' keyword do in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

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
raja
Published on 23-Nov-2021 07:25:10
Advertisements