Complete the code to delegate the print function to the printer object.
class Printer { fun print() { println("Printing document") } } class Document(val printer: Printer) { fun print() = printer.[1]() }
The print function in Document delegates the call to the print function of the Printer object.
Complete the code to use Kotlin's delegation syntax for the interface Printer.
interface Printer {
fun print()
}
class RealPrinter : Printer {
override fun print() {
println("Real printing")
}
}
class Document(printer: Printer) : Printer by [1] {
}
fun main() {
val doc = Document(RealPrinter())
doc.print()
}The class Document delegates the Printer interface implementation to the printer object passed in the constructor.
Fix the error by completing the code to delegate the interface correctly.
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) {
println("Log: $message")
}
}
class Service : Logger by [1] {
}
fun main() {
val service = Service()
service.log("Started")
}The delegation requires an instance of ConsoleLogger, so ConsoleLogger() is correct.
Fill both blanks to create a class that delegates Logger and adds a new function.
interface Logger {
fun log(message: String)
}
class FileLogger : Logger {
override fun log(message: String) {
println("File log: $message")
}
}
class AppLogger([1]: Logger) : Logger by [2] {
fun error(message: String) {
log("Error: $message")
}
}The constructor parameter logger is used to delegate the Logger interface.
Fill all three blanks to implement delegation with an additional method in Kotlin.
interface Speaker {
fun speak()
}
class Human : Speaker {
override fun speak() {
println("Hello!")
}
}
class Robot([1]: Speaker) : Speaker by [2] {
fun compute() {
println("Computing...")
}
}
fun main() {
val robot = Robot([3])
robot.speak()
robot.compute()
}The constructor parameter human is delegated to implement Speaker, and an instance Human() is passed when creating Robot.