Bird
Raised Fist0
Kotlinprogramming~20 mins

Class delegation with by keyword in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Delegation Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of class delegation example
What is the output of this Kotlin code using class delegation with the by keyword?
Kotlin
interface Printer {
    fun printMessage()
}

class ConsolePrinter : Printer {
    override fun printMessage() {
        println("Printing to console")
    }
}

class DelegatingPrinter(printer: Printer) : Printer by printer

fun main() {
    val printer = ConsolePrinter()
    val delegatingPrinter = DelegatingPrinter(printer)
    delegatingPrinter.printMessage()
}
APrinting to console
BNo output
CRuntime exception
DCompilation error
Attempts:
2 left
πŸ’‘ Hint
Remember that the by keyword delegates interface implementation to the given object.
❓ Predict Output
intermediate
2:00remaining
Delegation with method override
What will be printed when running this Kotlin code that uses delegation but overrides one method?
Kotlin
interface Speaker {
    fun speak()
    fun shout()
}

class LoudSpeaker : Speaker {
    override fun speak() = println("Speaking softly")
    override fun shout() = println("SHOUTING")
}

class CustomSpeaker(speaker: Speaker) : Speaker by speaker {
    override fun speak() = println("Custom speaking")
}

fun main() {
    val loudSpeaker = LoudSpeaker()
    val customSpeaker = CustomSpeaker(loudSpeaker)
    customSpeaker.speak()
    customSpeaker.shout()
}
A
Speaking softly
SHOUTING
B
Custom speaking
SHOUTING
C
Custom speaking
Speaking softly
D
SHOUTING
Custom speaking
Attempts:
2 left
πŸ’‘ Hint
Delegation forwards calls except for overridden methods in the delegating class.
πŸ”§ Debug
advanced
2:00remaining
Identify the error in delegation usage
This Kotlin code tries to delegate an interface but causes a compilation error. What is the cause?
Kotlin
interface Calculator {
    fun add(a: Int, b: Int): Int
}

class SimpleCalculator : Calculator {
    override fun add(a: Int, b: Int) = a + b
}

class Delegator : Calculator by SimpleCalculator() {
    fun subtract(a: Int, b: Int) = a - b
}

fun main() {
    val d = Delegator()
    println(d.add(5, 3))
    println(d.subtract(5, 3))
}
ANo error, code runs and prints 8 and 2
BError because Delegator must implement subtract() from Calculator
CError because SimpleCalculator() cannot be used directly in delegation
DError because Delegator does not have a primary constructor
Attempts:
2 left
πŸ’‘ Hint
Delegation only requires implementing interface methods; extra methods are allowed.
❓ Predict Output
advanced
2:00remaining
Delegation with multiple interfaces
What is the output of this Kotlin program that delegates two interfaces using separate objects?
Kotlin
interface Writer {
    fun write()
}

interface Reader {
    fun read()
}

class FileWriter : Writer {
    override fun write() = println("Writing to file")
}

class FileReader : Reader {
    override fun read() = println("Reading from file")
}

class FileHandler(writer: Writer, reader: Reader) : Writer by writer, Reader by reader

fun main() {
    val writer = FileWriter()
    val reader = FileReader()
    val handler = FileHandler(writer, reader)
    handler.write()
    handler.read()
}
ACompilation error due to multiple delegation
B
Reading from file
Writing to file
C
Writing to file
Reading from file
DRuntime exception due to ambiguous delegation
Attempts:
2 left
πŸ’‘ Hint
Kotlin supports delegation of multiple interfaces by separate objects.
🧠 Conceptual
expert
2:00remaining
Understanding delegation and method resolution
Consider a Kotlin class Master that delegates interface Worker to an object but also overrides one method. Which statement is true about method calls on Master?
AAll interface methods are forwarded to the delegate object, ignoring any overrides in Master.
BDelegation disables method overriding; Master cannot override any interface method.
CMaster must implement all interface methods explicitly; delegation is only for property access.
DCalls to overridden methods in Master execute Master’s code; other interface methods are forwarded to the delegate object.
Attempts:
2 left
πŸ’‘ Hint
Delegation forwards calls except when the delegating class overrides the method.

Practice

(1/5)
1. What does the by keyword do in Kotlin class delegation?
easy
A. It overrides all methods of a class.
B. It creates a new instance of a class.
C. It marks a class as abstract.
D. It lets a class reuse another class's implementation automatically.

Solution

  1. Step 1: Understand the role of by keyword

    The by keyword in Kotlin is used for class delegation, which means one class can reuse the implementation of another class without rewriting the code.
  2. Step 2: Identify what by does

    It automatically forwards calls to the delegated class, so the delegating class behaves like the delegated one.
  3. Final Answer:

    It lets a class reuse another class's implementation automatically. -> Option D
  4. Quick Check:

    Delegation = reuse implementation [OK]
Hint: Remember: by means reuse another class's code [OK]
Common Mistakes:
  • Thinking by creates a new instance
  • Confusing by with inheritance
  • Assuming by overrides methods automatically
2. Which of the following is the correct syntax to delegate interface Printer to class ConsolePrinter in Kotlin?
easy
A. class MyPrinter : Printer by ConsolePrinter()
B. class MyPrinter implements Printer by ConsolePrinter()
C. class MyPrinter extends Printer by ConsolePrinter()
D. class MyPrinter delegate Printer to ConsolePrinter()

Solution

  1. Step 1: Recall Kotlin delegation syntax

    In Kotlin, delegation uses the syntax: class ClassName : InterfaceName by instance.
  2. Step 2: Match the correct syntax

    class MyPrinter : Printer by ConsolePrinter() matches this pattern exactly: class MyPrinter : Printer by ConsolePrinter().
  3. Final Answer:

    class MyPrinter : Printer by ConsolePrinter() -> Option A
  4. Quick Check:

    Syntax = class X : Interface by instance [OK]
Hint: Use colon and 'by' for delegation syntax [OK]
Common Mistakes:
  • Using 'implements' or 'extends' keywords (Java style)
  • Writing 'delegate' keyword which doesn't exist
  • Missing colon before interface name
3. What is the output of this Kotlin code?
interface Logger {
    fun log(msg: String)
}

class ConsoleLogger : Logger {
    override fun log(msg: String) {
        println("Console: $msg")
    }
}

class AppLogger(logger: Logger) : Logger by logger

fun main() {
    val logger = AppLogger(ConsoleLogger())
    logger.log("Hello")
}
medium
A. No output
B. Console: Hello
C. Error: log() not implemented
D. Hello

Solution

  1. Step 1: Understand delegation in AppLogger

    The class AppLogger delegates Logger interface to the passed logger instance, which is ConsoleLogger.
  2. Step 2: Trace the log call

    Calling logger.log("Hello") calls ConsoleLogger.log, which prints "Console: Hello".
  3. Final Answer:

    Console: Hello -> Option B
  4. Quick Check:

    Delegation calls delegated method output [OK]
Hint: Delegated methods run from the delegated instance [OK]
Common Mistakes:
  • Expecting just 'Hello' without prefix
  • Thinking delegation requires manual override
  • Assuming no output because of delegation
4. Identify the error in this Kotlin code using class delegation:
interface Speaker {
    fun speak()
}

class Human : Speaker {
    override fun speak() {
        println("Hello")
    }
}

class Robot(speaker: Speaker) : Speaker {
    speak()
}
medium
A. Missing delegation with 'by' keyword in Robot class.
B. Robot class should not implement Speaker interface.
C. Human class must not override speak().
D. speak() method call is correct as is.

Solution

  1. Step 1: Check Robot class declaration

    Robot implements Speaker but does not delegate or implement speak() method itself.
  2. Step 2: Identify missing delegation

    Robot should delegate Speaker to the passed speaker instance using by speaker to avoid error.
  3. Final Answer:

    Missing delegation with 'by' keyword in Robot class. -> Option A
  4. Quick Check:

    Delegation needs 'by' keyword [OK]
Hint: Delegate with 'by' or implement all methods [OK]
Common Mistakes:
  • Calling method directly without delegation
  • Forgetting to use 'by' keyword
  • Assuming interface methods auto-implement
5. You want to create a class SmartSpeaker that delegates Speaker interface to a Human instance but adds a new method playMusic(). Which is the best way to do this?
hard
A. class SmartSpeaker : Human() { fun playMusic() = println("Playing music") }
B. class SmartSpeaker : Speaker { val human = Human() override fun speak() = human.speak() fun playMusic() = println("Playing music") }
C. class SmartSpeaker(human: Human) : Speaker by human { fun playMusic() { println("Playing music") } }
D. class SmartSpeaker(human: Human) : Speaker { fun playMusic() = println("Playing music") }

Solution

  1. Step 1: Understand delegation with added methods

    Using by human delegates all Speaker methods to Human automatically.
  2. Step 2: Add new method in delegating class

    We can add playMusic() directly in SmartSpeaker without affecting delegation.
  3. Final Answer:

    class SmartSpeaker(human: Human) : Speaker by human { fun playMusic() { println("Playing music") } } -> Option C
  4. Quick Check:

    Delegate with 'by' and add methods [OK]
Hint: Delegate with 'by' and add new methods in class body [OK]
Common Mistakes:
  • Not delegating interface methods properly
  • Extending class instead of delegating interface
  • Forgetting to implement interface methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard