Understanding delegation and by keyword in Kotlin

Are you struggling to understand delegation and `by` keyword in Kotlin? In this blog, we’ll try to simplify it.

What is delegation?

Delegation refers to the transfer of responsibility from one thing to another.

In Programming, Delegation allows you to use the functions and properties of another class or object as if they are part of your own class.

Here’s a simple example

class DelegateClass {
  fun doSomething() = println("I'm doing something!")
}

class DelegatingClass(val delegate: DelegateClass) {
  fun doSomething() = delegate.doSomething()
}

val delegateClass = DelegateClass()
val delegatingClass = DelegatingClass(delegateClass)
delegatingClass.doSomething() // prints "I'm doing something!"

In this example, the DelegatingClass delegates the doSomething function to the DelegateClass. This means that when doSomething is called on the DelegatingClass, it will actually be calling the doSomething function of the DelegateClass.

Now, what does the by keyword do in Kotlin?

Consider below example,

class DelegatingClass(val delegate: DelegateClass) : DelegateClass by delegate {
  // Additional code
}

class DelegateClass {
  fun doSomething() = println("I'm doing something!")
}

val delegateClass = DelegateClass()
val delegatingClass = DelegatingClass(delegateClass)
delegatingClass.doSomething() // prints "I'm doing something!"

In this version of the code, the DelegatingClass is defined as a subclass of the DelegateClass, using the by keyword to specify that it will delegate the implementation of the doSomething function to the DelegateClass.

This means that when the doSomething function is called on an instance of the DelegatingClass, the function of the same name in the DelegateClass will be executed. The DelegatingClass acts as a “proxy” for the DelegateClass, forwarding function calls to it.

The by keyword is used to establish this relationship between the DelegatingClass and the DelegateClass. It tells the compiler that the DelegatingClass will delegate the implementation of the doSomething function to the DelegateClass.

Share with your friends

Leave a Reply

Your email address will not be published. Required fields are marked *