Access the instance by which methods of an interface are delegated inside of the class

131 Views Asked by At

Is there a way to access the instance by which methods of an interface are delegated inside of the class?

class Class1(): Interface2 by Class2() { // NOTE: Class2() is here a concrete implementation by which the methods of Interface2 are delegated.
  // I want to access the instance by which the Interface2 is delegated (Class2()) in here.
}

Fore now I do it like this:

private val class2Instance = Class2()
class Class1(): Interface2 by class2Instance { // NOTE: Class2() is here a concrete implementation by which the methods of Interface2 are delegated.
  val class2: Class2 by ::class2Instance // the value class2 now grants me access to class2Instance
}

But I don't think this is a good way, because the class has to access a value that is declared outside any class.

1

There are 1 best solutions below

2
Karsten Gabriel On

You can make Class2 a property and constructor parameter of Class1 and then delegate by that parameter:

class Class1(val class2: Class2): Interface2 by class2

That way you do not need the reference to the class2Interface defined outside the Class1 from inside Class1, but you have to pass it as constructor parameter:

val class1 = Class1(class2Instance)