-
Notifications
You must be signed in to change notification settings - Fork 24
what is delegation in kotlin
Devrath edited this page Feb 27, 2024
·
26 revisions
π²πΎπ½ππ΄π½ππ |
---|
Deligating objects |
Property Deligation |
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 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