Complete the code to inherit from the base class.
open class Base { fun greet() = println("Hello from Base") } class Derived : [1]() { } fun main() { val obj = Derived() obj.greet() }
In Kotlin, to inherit from a class, use a colon followed by the base class name. Here, Derived inherits from Base.
Complete the code to delegate the interface implementation.
interface Printer {
fun print()
}
class RealPrinter : Printer {
override fun print() = println("Printing from RealPrinter")
}
class Delegator([1] printer: Printer) : Printer by printer
fun main() {
val realPrinter = RealPrinter()
val delegator = Delegator(realPrinter)
delegator.print()
}val or var before the parameter.private which is not allowed here.To delegate an interface in Kotlin, the constructor parameter must be a val or var so it can be used for delegation.
Fix the error in the delegation syntax.
interface Speaker {
fun speak()
}
class Person : Speaker {
override fun speak() = println("Person speaking")
}
class Robot([1] speaker: Speaker) : Speaker by speaker
fun main() {
val person = Person()
val robot = Robot(person)
robot.speak()
}private which is not allowed for delegation parameters.val or var.The delegation parameter must be a property, so it needs val or var. Here, val is correct.
Fill both blanks to create a delegated class that overrides a method.
interface Logger {
fun log(message: String)
}
class ConsoleLogger : Logger {
override fun log(message: String) = println("Console: $message")
}
class CustomLogger([1] logger: Logger) : Logger by logger {
override fun log(message: String) {
println("Custom log start")
logger.[2](message)
println("Custom log end")
}
}
fun main() {
val consoleLogger = ConsoleLogger()
val customLogger = CustomLogger(consoleLogger)
customLogger.log("Hello")
}var instead of val (both work but val is preferred).print instead of log.The constructor parameter must be a property, so use val. To call the delegated method, use log.
Fill both blanks to create a delegated class that adds behavior before and after delegation.
interface Notifier {
fun notify(message: String)
}
class EmailNotifier : Notifier {
override fun notify(message: String) = println("Email: $message")
}
class AdvancedNotifier([1] notifier: Notifier) : Notifier by notifier {
override fun notify(message: String) {
println("Start notification")
notifier.[2](message)
println("End notification")
}
fun extra() = println("Extra functionality")
}
fun main() {
val emailNotifier = EmailNotifier()
val advNotifier = AdvancedNotifier(emailNotifier)
advNotifier.notify("Meeting at 10")
}print instead of notify.val before the constructor parameter.The constructor parameter must be a property, so use val. To call the delegated method, use notify.