Class delegation with by keyword
📖 Scenario: Imagine you are building a simple app to manage different types of workers in a company. Some workers have special skills, but you want to reuse existing skill implementations without rewriting code.
🎯 Goal: You will create a Kotlin program that uses class delegation with the by keyword to share behavior between classes easily.
📋 What You'll Learn
Create an interface called
Worker with a function work() that returns a String.Create a class called
BasicWorker that implements Worker and returns "Working hard" from work().Create a class called
Manager that delegates Worker behavior to a BasicWorker instance using the by keyword.Print the result of calling
work() on a Manager instance.💡 Why This Matters
🌍 Real World
Class delegation helps reuse code and share behavior between classes without repeating code. It is useful in apps with many similar roles or behaviors.
💼 Career
Understanding delegation is important for Kotlin developers to write clean, maintainable code and use language features effectively in real projects.
Progress0 / 4 steps