Search code examples
kotlindelegatesoverriding

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


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?


Solution

  • 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.