Koltin:"abstract member cannot be accessed directly" 使用委托时("by" 关键字)

Koltin: "abstract member cannot be accessed directly" when using delegation ("by" keyword)

这是示例代码:

class PurchaseHistory: MutableList<PurchaseInfo> by mutableListOf() {
    override fun add(element: PurchaseInfo): Boolean {
        // ... some code
        return super.add(element)
    }
}

但是,我得到 abstract member cannot be accessed directly。当我从 class 外部使用原始方法时,我没有遇到任何问题,但为什么我不能从它内部做同样的事情?

我相信您会收到此错误,因为您尝试调用的 add 方法实际上并不在 PurchaseHistory 的超级 class.

要为所欲为,您可以保留要委派给的对象的句柄。例如,您可以将其存储为 属性:

class PurchaseHistory(
    private val backingList: MutableList<PurchaseInfo> = mutableListOf()
): MutableList<PurchaseInfo> by backingList {
    override fun add(element: PurchaseInfo): Boolean {
        // ... some code
        return backingList.add(element)
    }
}

另一种选择是直接扩展 MutableList 的实现(例如 ArrayList),而不是委托实现,但这可能不适合您。

您正在尝试从未定义的接口 MutableList 调用方法。

只需让 ArrayList 成为你的 class 的晚餐,你应该会有好的结果:

class PurchaseHistory: ArrayList<PurchaseInfo>() {

    override fun add(element: Int): Boolean {
        // ... some code
        return super.add(element)
    }
}