【问题标题】:Access the instance by which methods of an interface are delegated inside of the class访问在类内部委托接口方法的实例
【发布时间】: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


    【解决方案1】:

    您可以将Class2 设为Class1 的属性和构造函数参数,然后通过该参数进行委托:

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

    这样你就不需要从Class1 内部对Class1 外部定义的class2Interface 的引用,但你必须将它作为构造函数参数传递:

    val class1 = Class1(class2Instance)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2018-04-02
      • 2021-05-27
      相关资源
      最近更新 更多