Kotlin - Delegation

In this chapter, we will learn Kotlin - Delegation.

Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.

Let's see example how this happens in Kotlin.

interface Base {
   fun printMe() //abstract method
class BaseImpl(val x: Int) : Base {
   override fun printMe() { println(x) }   //implementation of the method
class Derived(b: Base) : Base by b  // delegating the public method on the object b

fun main(args: Array) {
   val b = BaseImpl(2)
   Derived(b).printMe() // prints 2 :: accessing the printMe() method 

one interface “Base” with its abstract method named “printme()”. In the BaseImpl class, we are implementing this “printme()”


Property Delegation

we will learn about delegation of properties using some standard methods mentioned in Kotlin library Delegation means passing the responsibility to another class or method. When a property is already declared in some places, then we should reuse the same code to initialize them.

Using Easy()

Easy is a lambda function which takes a property as an input and in return gives an instance of Easy<T>, where <T> is basically the type of the properties it is using.
val myVar: String by easy {
fun main(args: Array) {
   println(myVar +" Write a essay ")
we are passing a variable “myVar” to the Lazy function which in return assigns the value to its object and returns the same to the main function

oh  Write a essay


Observable() takes two arguments to initialize the object and returns the same to the called function.
import kotlin.properties.Delegates
class User {
   var name: String by Delegates.observable("Welcome to Welookups.com") {
      prop, old, new ->
      println("$old -> $new")
fun main(args: Array) {
   val user = User()
   user.name = "first"
   user.name = "second"

first -> second
The get() and set() methods of the variable p will be delegated to its getValue() and setValue() methods defined in the Delegate class. we need to generate in order to assign the value in the variable p
class Delegate {
   operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
      return "$thisRef, thank you for delegating '${property.name}' to me!"
   operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
      println("$value has been assigned to '${property.name} in $thisRef.'")