Reputation: 1732
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?
Upvotes: 3
Views: 803
Reputation: 37710
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.
Upvotes: 2
Reputation: 654
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)
}
}
Upvotes: 0