Image from : Christina Morillo

Kotlin tries to Delegate

Randy Arba
3 min readMay 16, 2022

--

What is Delegation? based on vocabulary Delegation definition means, the act of empowering to act for another, the delegation of responsibilities. A common case is when you tell someone to get your mail for you. The definition of a delegate is a representative authorized to speak or act for others.

Giving one responsibility of doing work to another one.

So what relation with Kotlin language, Kotlin has a property called Delegate properties, the purpose of this properties is same what vocabulary. Kotlin delegate can assign work to another. Below is an example I use TeamLead and TeamMember concepts.

We have an Interface Human class that has leadDailyStandup() functions. After that, we will inherit those class into TeamLead class and override leadDailyStandup() functions.

After TeamLead class is already defined, so we will give another team member opportunity to lead daily standup. TeamLeader needs to try to increase ownership of team members and learn leadership using daily standup as lead on the meeting so they delegate it. The leader will give them the template and train how to lead for daily standup meetings.

We can create another class that inherits the Human class and passes TeamLead type data as an argument which means one of the responsibilities will pass into another class.

Create an object-based class that is already created on main() function and execute, below is the example of the main function()

Below is the result of the above, we pass teamLead parameter into TeamMember class we called Helper, and the conclusions of the output are Team lead will do help team members for daily standup and himself.

The code below actually can be improved and reduce the line code using delegate properties from Kotlin. Removing boilerplate and turn into one line.

Before using Kotlin delegate
After using Kotlin delegate.

The purpose remains the same as the result, it’s just reducing the line of code. Kotlin has several keywords and APIs that need to explore, for example, Delegate properties. The real case using Kotlin delegate is, related the abstraction and inheritance.

The result is based code above, Team Lead can delegate to Team members after he trains them for daily standup.

--

--