Interface delegation with by in Kotlin
Level 5321 keystrokes
Printer by printer makes Document implement Printer by forwarding every interface method to the given object, without writing the forwarding code by hand. Calling print() inside Document therefore runs ConsolePrinter's print().
Kotlin code
// The interface to delegate1interface Printer { // A single abstract method that takes the text to print2 fun print(text: String)3}4 // A concrete implementation that writes to the console5class ConsolePrinter : Printer { // Prints the text with a [Console] prefix6 override fun print(text: String) = println("[Console] $text")7}8 // by printer: the compiler generates the Printer methods and forwards them to printer9class Document(printer: Printer) : Printer by printer { // Document adds its own method on top of the delegated ones10 fun printTitle(title: String) { // The member print() (forwarded to printer) is chosen over the top-level print()11 print("Title: $title")12 }13}14 // Pass the object that will do the actual work15val doc = Document(ConsolePrinter())// Prints [Console] Title: Hello16doc.printTitle("Hello")Output
[Console] Title: Hello
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 9)× 9:× 7"× 6{× 4}× 4=× 2$× 2.× 1[× 1