0
0
Kotlinprogramming~30 mins

Why delegation avoids inheritance in Kotlin - See It in Action

Choose your learning style9 modes available
Why Delegation Avoids Inheritance in Kotlin
📖 Scenario: Imagine you are building a simple app where different types of workers perform tasks. You want to share common behavior without making a complex family tree of classes.
🎯 Goal: You will create a Kotlin example showing how delegation can be used to share behavior between classes without using inheritance.
📋 What You'll Learn
Create an interface called Worker with a function work()
Create a class called Developer that implements Worker and prints "Writing code" when work() is called
Create a class called Manager that uses delegation to a Worker instance
Show how Manager can delegate work() to a Developer instance
Print the output of calling work() on the Manager instance
💡 Why This Matters
🌍 Real World
Delegation is used in many Kotlin projects to share behavior without deep inheritance trees, making code easier to change and test.
💼 Career
Understanding delegation helps you write cleaner Kotlin code and is a valuable skill for Android and backend Kotlin development jobs.
Progress0 / 4 steps
1
Create the Worker interface and Developer class
Create an interface called Worker with a function work() that returns Unit. Then create a class called Developer that implements Worker and overrides work() to print "Writing code".
Kotlin
Need a hint?

Use interface keyword for Worker. Implement it in Developer with override fun work().

2
Create Manager class that delegates to Worker
Create a class called Manager that takes a worker parameter of type Worker in its constructor. Use Kotlin's delegation syntax : Worker by worker to delegate work() calls to the passed worker.
Kotlin
Need a hint?

Use class Manager(private val worker: Worker) : Worker by worker to delegate.

3
Create Developer instance and Manager instance delegating to Developer
Create a variable called dev and assign it a new Developer() instance. Then create a variable called mgr and assign it a new Manager(dev) instance.
Kotlin
Need a hint?

Use val dev = Developer() and val mgr = Manager(dev).

4
Call work() on Manager instance and print output
Call work() on the mgr variable and print the output.
Kotlin
Need a hint?

Just call mgr.work() to see delegation in action.