3

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 the original method from outside the class, I don't encounter any issues, but why can't I do the same thing from inside of it?

Lover of Structure
  • 1,561
  • 3
  • 11
  • 27
Amin Guermazi
  • 1,632
  • 9
  • 19

2 Answers2

2

You get this error because the add method you're trying to call is not really in PurchaseHistory's super class (because it doesn't have a superclass), and thus the error tells you that you cannot just call an interface (abstract) method using super.

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.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
0

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)
    }
}