Delegates in Kotlin
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Today I will be writing about my understanding regarding the delegates in Kotlin.
The english meaning of Delegation simply means transferring the responsibility of doing something to someone else.
In context of Koltin, it means passing the responsibility of performing one task to another object which is called the Delegate, since it is the one performing the real task.
While this thing is achievable by using higherOrder functions in Kotlin, yet we generally use delegates to reduce heavy boilder plate code which we would have otherwise written using inheritance concepts.
I will illustrate two popular delegations using the below code -
Here we have two classes namely JuniorCoder and SeniorCoder, where the first category can only write code, but the second category can write and review code too.
This is the power of Delegation or the by keyword, instead of making SeniorCoder class implement the Coder interface we have delegated the common tasks to the JuniorCoder class by writing this single line -
领英推荐
class SeniorCoder(val name: String): Coder by JuniorCoder(name)
Check the logs for the above code -
Now let us understand the variable delegation, where we delegate the variable initialization to lazy which initializes it when the variable is first accessed. Take a look at the below code -
Here, we are initializing the varibale myString using lazy, and the result is that we can only see the string "Initializing the string" printed single time, at the time of first access. And after that no matter how many times we access it, it is just readonly with the value as "Sid". Check the below logs -
I hope we learnt something from this explaination on delegates in Kotlin. Thanks for reading. Happy coding.