Skip to content

Instantly share code, notes, and snippets.

@uberto
Created May 12, 2018 19:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uberto/63a9ec188e347296898764c0cddb1a96 to your computer and use it in GitHub Desktop.
Save uberto/63a9ec188e347296898764c0cddb1a96 to your computer and use it in GitHub Desktop.
Multiple Inheritance via Delegation in Kotlin
package com.gamasoft.delegation
import assertk.assert
import assertk.assertions.isEqualTo
import org.junit.Test
//https://kotlinlang.org/docs/reference/delegation.html
interface Printer {
fun print(msg: String)
}
class PrinterStdOut() : Printer {
override fun print(msg: String) = println(msg)
}
interface Scanner {
fun scan(): String
}
class ScannerConst(val c: String) : Scanner {
override fun scan(): String = c
}
class AlsoPrinter(p: Printer) : Printer by p {
fun otherMethod(){
///do something else
}
}
class MultiFunction(p: Printer, s: Scanner) : Printer by p, Scanner by s
internal class DelegationTest {
@Test
fun delegateInheritance() {
val ap = AlsoPrinter(PrinterStdOut())
ap.print("hello")
assert(ap is Printer)
}
@Test
fun multipleInheritance() {
val mf = MultiFunction(PrinterStdOut(), ScannerConst("hello"))
val msg = mf.scan()
assert( msg).isEqualTo("hello")
mf.print(msg)
assert(mf is Scanner)
assert(mf is Printer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment