Skip to content

what is delegation in kotlin

Devrath edited this page Feb 28, 2024 · 26 revisions
π™²π™Ύπ™½πšƒπ™΄π™½πšƒπš‚
What is meant by delegation
Deligating objects
Property Deligation

What is meant by delegation

  • Delegation is an object-oriented pattern that helps in code reuse without using inheritance.
  • Kotlin supports this natively.

Deligating objects

Delegation in kotlin means, Delegating the responsibility to other objects.

Observation

  • Notice in the place without using the by delegation we can observe there is more boiler code present.
  • It is handled in Android by using the by keyword and as noticed, Significantly the boilerplate code is reduced.

Output

David is studying
<--------------->
David is studying

Code

fun main(args: Array<String>) {

    val david = David()
    val demoOne = SchoolDemoOne(david)
    val demoTwo = SchoolDemoTwo(david)

    demoOne.studying()
    println("<--------------->")
    demoTwo.studying()

}

/**
 * Studying can perform the action of studying
 */
interface Student {
    fun studying()
}


/**
 * Concrete implementation for a student
 */
class David : Student {
    override fun studying() {
        println("David is studying")
    }
}

/**
 * Delegation done but by not using `By` feature of kotlin
 */
class SchoolDemoOne(
    private val student : Student
): Student{
    override fun studying() {
        student.studying()
    }
}

/**
 * Delegation done but by using `By` feature of kotlin
 * Notice we removed the boilerplate code
 */
class SchoolDemoTwo(
    private val student : Student
): Student by student

Property delegation

Clone this wiki locally