0
0
Kotlinprogramming~15 mins

Class delegation with by keyword in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Worker interface and BasicWorker class
Create an interface called Worker with a function work() that returns a String. Then create a class called BasicWorker that implements Worker and its work() function returns the exact string "Working hard".
Kotlin
Need a hint?

Use interface to define Worker. Implement work() in BasicWorker to return the string exactly.

2
Create Manager class delegating Worker to BasicWorker
Create a class called Manager that implements Worker by delegating to a BasicWorker instance using the by keyword. Inside Manager, declare a primary constructor parameter called worker of type Worker and delegate Worker to it.
Kotlin
Need a hint?

Use class Manager(private val worker: Worker) : Worker by worker to delegate all Worker functions to the worker instance.

3
Create a Manager instance delegating to BasicWorker
Create a variable called manager and assign it a new Manager instance that delegates to a new BasicWorker instance.
Kotlin
Need a hint?

Use val manager = Manager(BasicWorker()) to create the instance.

4
Print the work result from Manager
Write a println statement to print the result of calling work() on the manager variable.
Kotlin
Need a hint?

Use println(manager.work()) to show the delegated work result.