A question about delegation


#1

given follwoing code :

trait Base {   fun print() }
class BaseImpl(val x : Int) : Base {
  override fun print() { print(x) }
}
class Derived : Base by BaseImpl(10) {
  fun test() {
  //Can I access to BaseImpl instance here ?
  }
}
fun main(args : Array<String>) {
  Derived().print() // prints 10
}

Is there a way to access to  BaseImpl instance, inside test method ?


#2

You can not access to BaseImpl instance in your example. But now you can write like:

``

class Derived(val impl: Base = BaseImpl(10)) : Base by impl {
  fun test() {
  //Can I access to BaseImpl instance here ?
  }
}

or:
``

val impl: Base = BaseImpl(10)

class Derived : Base by impl {
  fun test() {
  //Can I access to BaseImpl instance here ?
  }
}

Additionally you can vote and watch related issue KT-83


#3

Thanks Bashor,

For some reason, I can’t touch the constructor, so the only available option is the second one. Altough It’s not the ideal solution but seems the only possible one.