Challenge - 5 Problems
Delegation vs Inheritance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of delegation example
What is the output of this Kotlin code using delegation?
Kotlin
interface Printer { fun print() } class RealPrinter : Printer { override fun print() { println("Printing from RealPrinter") } } class Delegator(printer: Printer) : Printer by printer fun main() { val realPrinter = RealPrinter() val delegator = Delegator(realPrinter) delegator.print() }
Attempts:
2 left
💡 Hint
Delegation forwards calls to the provided object.
✗ Incorrect
The Delegator class delegates the print() call to RealPrinter, so the output is from RealPrinter.
❓ Predict Output
intermediate2:00remaining
Output of inheritance example
What is the output of this Kotlin code using inheritance?
Kotlin
open class Printer { open fun print() { println("Printing from Printer") } } class ChildPrinter : Printer() { override fun print() { println("Printing from ChildPrinter") } } fun main() { val printer: Printer = ChildPrinter() printer.print() }
Attempts:
2 left
💡 Hint
Inheritance allows overriding methods.
✗ Incorrect
ChildPrinter overrides print(), so calling print() on a ChildPrinter instance prints its own message.
🧠 Conceptual
advanced2:00remaining
Choosing delegation over inheritance
Which scenario best justifies using delegation instead of inheritance in Kotlin?
Attempts:
2 left
💡 Hint
Delegation allows flexible behavior without inheritance constraints.
✗ Incorrect
Delegation allows an object to use another object's functionality without inheriting from it, enabling loose coupling and runtime behavior changes.
❓ Predict Output
advanced2:00remaining
Output with delegation and overridden method
What is the output of this Kotlin code where delegation is combined with an overridden method?
Kotlin
interface Speaker { fun speak() } class EnglishSpeaker : Speaker { override fun speak() { println("Hello") } } class CustomSpeaker(private val speaker: Speaker) : Speaker by speaker { override fun speak() { println("Custom speak start") speaker.speak() println("Custom speak end") } } fun main() { val english = EnglishSpeaker() val custom = CustomSpeaker(english) custom.speak() }
Attempts:
2 left
💡 Hint
Overriding a delegated method allows adding behavior before and after delegation.
✗ Incorrect
CustomSpeaker overrides speak() to add prints before and after calling the delegated speaker's speak().
🧠 Conceptual
expert3:00remaining
Why avoid inheritance for behavior reuse?
Why might inheritance be a poor choice for reusing behavior compared to delegation in Kotlin?
Attempts:
2 left
💡 Hint
Think about coupling and flexibility differences.
✗ Incorrect
Inheritance tightly couples classes and fixes behavior at compile time, while delegation composes behavior and allows changing it dynamically.