-
Notifications
You must be signed in to change notification settings - Fork 22
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
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.
David is studying
<--------------->
David is studying
fun 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-activity
to 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-1
that 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-2
that 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-1
andfunctionality-2
in 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