Kotlin interface inheritance and delgation
The Printer is the base class, the interface. The InkPrinter and LaserPrinter implements the interface by inheriting from the interface class Printer and override it’s functions. The PrinterWrapper takes the InkPrinter or LaserPrinter and using the by clause to make all the functions in the Printer interfave available for PrinterWrapper to use.
interface Printer { fun print() } class InkPrinter(val s: String) : Printer { override fun print() { println("Ink printer: ${s}") } } class LaserPrinter(val s: String) : Printer { override fun print() { println("Laser printer: ${s}") } } /* The by-clause in the supertype list for PrinterWrapper will make all the functions in the interface Printer available for PrinterWrapper to use. */ class PrinterWrapper(var p: Printer) : Printer by p { fun whatisthis() { println("This is a printer wrapper!") } } fun main(args: Array) { val ink = InkPrinter("Hello World!") val laser = LaserPrinter("Hello World!") PrinterWrapper(ink).print() PrinterWrapper(ink).whatisthis() println("--------------------------------------------------") PrinterWrapper(laser).print() PrinterWrapper(laser).whatisthis() }
References:
https://kotlinlang.org/docs/reference/delegation.html
https://en.wikipedia.org/wiki/Delegation_pattern
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts