-
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
Delegation in kotlin means, Delegating the responsibility to other objects.
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