代码之家  ›  专栏  ›  技术社区  ›  Ahmad Shahwan

Kotlin:指未由构造函数传递的委托

  •  0
  • Ahmad Shahwan  · 技术社区  · 2 年前

    我想用 Kotlin delegation 在特定的背景下。

    • 不应在构造函数中传递委托。
    • 我想保留对委托的引用,以便以后在代码中使用。从我覆盖的方法中 printMessage() ,我仍然需要像你一样给代表打电话 super.printMessage() 在多态性遗传中。

    我可以通过在 by 条款( class Derived() : Base by BaseImpl(42) 使用 Kotlin's documentation example ).然而, 这会阻止我访问匿名委托,因为我知道无法引用它。

    我想做以下类似的事情。然而,下面的代码并没有编译错误 'this' is not defined in this context

    class Derived() : Base by this.b {
        
        val b: Base = BaseImpl(42)
        
        override fun printMessage() {
            b.printMessage()
            print("abc")
        }
    }
    

    我确实需要为我的每一个实例单独委派一名代表 Derived 班太感人了 b 作为一个全局变量,我不能选择。

    最接近我所需要的是构造函数的可选参数。这也不是一个好的选择,因为我不想让我的 衍生 与任意委托一起上课。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Tenfour04    2 年前

    您可以使用私有主构造函数和公共辅助构造函数来实现这一点:

    class Derived private constructor(val b: Base) : Base by b {
    
        constructor(): this(BaseImpl(42))
    
        override fun printMessage() {
            b.printMessage()
            print("abc")
        }
    }