nicola.de.fiorenze
01/02/2018, 5:03 PMinterface Base {
fun print()
fun getValue() : String
}
class BaseImpl : Base {
override fun print() { print(getValue()) }
override fun getValue(): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
class Derived(private val b: Base) : Base by b {
override fun getValue(): String = "hello"
}
fun main(args: Array<String>) {
val b = BaseImpl()
Derived(b).print() // prints 10
}
obviously the output is
Exception in thread "main" kotlin.NotImplementedError: An operation is not implemented: not implemented
at BaseImpl.getValue(Main.kt:12)
at BaseImpl.print(Main.kt:9)
at Derived.print(Main.kt)
at Main3Kt.main(Main.kt:22)
which is the cleanest way to refactor this snippet to specify in Derived
what should be used in BaseImpl.print()
?Andreas Sinz
01/02/2018, 5:08 PMBaseImpl
, but rather redirect method calls to BaseImpl
, so its still using its own print()
Andreas Sinz
01/02/2018, 5:09 PMgetValue()
Andreas Sinz
01/02/2018, 5:15 PMclass BaseWithCustomGetValue(val base: Base, val customGetValue: () -> String) : Base by base {
override fun getValue() = customGetValue()
}
class Derived(private val b: Base) : Base by BaseWithCustomGetValue(b, { "Hello" }) {
}