【发布时间】:2022-08-15 02:57:18
【问题描述】:
有没有办法访问在类内部委托接口的方法的实例?
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.
}
现在我这样做:
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
}
但我不认为这是一个好方法,因为类必须访问在任何类之外声明的值。
标签: kotlin delegation