- 
                Notifications
    
You must be signed in to change notification settings  - Fork 24
 
what is delegation in kotlin
        Devrath edited this page Feb 28, 2024 
        ·
        26 revisions
      
    - Delegation is an object-oriented pattern that helps in code reuse without using inheritance.
 - Kotlin supports this natively.
 
Delegation in kotlin means, Delegating the responsibility to other objects.
- Notice in the place without using the 
bydelegation we can observe there is more boiler code present. - It is handled in Android by using the 
bykeyword and as noticed, Significantly the boilerplate code is reduced. 
David is studying
<--------------->
David is studyingfun main(args: Array<String>) {
    val david = David()
    val demoOne = SchoolDemoOne(david)
    val demoTwo = SchoolDemoTwo(david)
    demoOne.studying()
    println("<--------------->")
    demoTwo.studying()
}
/**
 * Studying can act 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- With the property delegation, We can override the getter and setter methods and easily be able to share this behavior.
 - Basically once we override the properties, we can provide our own implementation that can be reused across multiple places where the same behavior is needed.
 Example
- We used to use the 
base-activityto have some behavior for all our activities or some of the activities, For this kind of we needed the inheritance there. - Well there is an alternative way of using inheritance, Well it is called delegation.
 - Consider the use case
- Say you have a functionality 
functionality-1that you want to use in some activity --> You create a base activity and add that functionality. You can use this base activity as a parent with any of your children. - Say now you have a functionality 
functionality-2that you want in some another activity --> You create another base activity and add that functionality. You again can use the base activity as a parent with children where you need. - Now if you want both 
functionality-1andfunctionality-2in some other scenario we might need a new base activity to be created - Use can use delegation to solve this.
 
 - Say you have a functionality 
 Demo
