gpt4 book ai didi

kotlin - 从重写中使用类委托(delegate)时调用(基)委托(delegate)函数

转载 作者:行者123 更新时间:2023-12-02 06:17:07 27 4
gpt4 key购买 nike

当重写 class delegation 实现的接口(interface)方法时,是否可以调用通常从重写函数中委托(delegate)给的类?类似于使用继承时调用 super 的方式。

来自documentation :

interface Base {
fun print()
}

class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}

class Derived(b: Base) : Base by b

fun main(args: Array<String>) {
val b = BaseImpl(10)
Derived(b).print() // prints 10
}

Note that overrides work as you might expect: The compiler will use your override implementations instead of those in the delegate object.

override fun print() { ... }

如何从此重写函数中调用 BaseImpl print() 函数?

用例是我想向此函数添加额外的逻辑,同时重用现有的实现。

最佳答案

由于 Base 是一个接口(interface),因此您无法真正对其调用 super(类似于 Java)。

相反,您需要将 b 声明为字段并直接使用它:

class Derived(val b: Base) : Base by b {
override fun print() {
b.print()
// ...
}
}

关于kotlin - 从重写中使用类委托(delegate)时调用(基)委托(delegate)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810973/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com