Hint: Delegation calls methods on passed instance, check which one is used [OK]
Common Mistakes:
Assuming FileLogger is used instead of ConsoleLogger
Expecting Application prefix in output
Thinking no output occurs without explicit print
4. Find the error in this Kotlin delegation code:
interface Worker {
fun work()
}
class Engineer : Worker {
override fun work() {
println("Engineering work")
}
}
class Manager(worker: Worker) : Worker {
override fun work() {
println("Managing")
}
}
medium
A. Manager should delegate work to Worker using 'by' keyword.
B. Engineer class must not override work method.
C. Interface Worker cannot be implemented by classes.
D. Manager class should not have a constructor parameter.
Solution
Step 1: Check delegation usage
Manager has a Worker parameter but does not delegate using 'by', so delegation is missing.
Step 2: Identify correct delegation syntax
To delegate, Manager should declare: class Manager(worker: Worker) : Worker by worker.
Final Answer:
Manager should delegate work to Worker using 'by' keyword. -> Option A
Quick Check:
Missing 'by' keyword for delegation = D [OK]
Hint: Delegation requires ': Interface by instance' syntax [OK]
Common Mistakes:
Thinking override is not needed in Engineer
Believing interfaces can't be implemented
Assuming constructor parameters are disallowed
5. You want to combine behaviors of two interfaces Reader and Writer in one class without inheritance. Which Kotlin approach best avoids inheritance problems?
hard
A. Copy all methods from Reader and Writer into one class manually.
B. Create a class that inherits from both interfaces directly.
C. Use inheritance from one interface and implement the other manually.
D. Use delegation to both interfaces by passing separate instances.
Solution
Step 1: Understand multiple inheritance issues
Inheriting from multiple interfaces can cause tight coupling and complexity.
Step 2: Use delegation to combine behaviors safely
Delegation allows combining behaviors by forwarding calls to separate instances, avoiding inheritance problems.
Final Answer:
Use delegation to both interfaces by passing separate instances. -> Option D
Quick Check:
Delegation combines behaviors safely = C [OK]
Hint: Delegate multiple interfaces to separate instances to avoid inheritance issues [OK]
Common Mistakes:
Trying multiple inheritance which Kotlin disallows
Manually copying methods causing code duplication
Mixing inheritance and manual implementation causing complexity
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.