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

Viewed 195

This is the sample code:

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

However, I am getting abstract member cannot be accessed directly. When I use original method from outside the class, I doesn't encounter any issues, but why can't I do the same thing from inside of it?

2 Answers

I believe you get this error because the add method you're trying to call is not really in PurchaseHistory's super class.

To do what you want, you can keep a handle to the object you are delegating to. For instance, you can store it as a property:

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

Another option is to directly extend an implementation of MutableList (such as ArrayList) instead of implementing by delegation, but that might not be an option for you.

You are trying to call method from interface MutableList which is not defined.

Just make ArrayList supper of your class, and you should have good result:

class PurchaseHistory: ArrayList<PurchaseInfo>() {

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