Hi guys! I have something like this: ``` interface...
# announcements
n
Hi guys! I have something like this:
Copy code
interface 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
Copy code
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()
?
a
@ndefiorenze There is no simple way to do that with delegation, because you are not really inheriting anything from
BaseImpl
, but rather redirect method calls to
BaseImpl
, so its still using its own
print()
easiest way would be to use inheritance instead of delegation, that way you can override
getValue()
with inheritance:
Copy code
class 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" }) {
}
👍 1