Implementation of MutableCollection


#1

Hello,

I’m trying to implement a use of the MutableCollection interface but I’m not sure how to continue. Here is what I have:

interface Base {
    ...
}

class A() : Base {
    ....
}

class B() : Base {
    ....
}

class C() : Base {
    ....
}

Ultimately, I want to be able to manipulate a collection of Base-like objects - whether that be a collection of A, a collection of B, etc…

So I tried to do this:

class MyColl : MutableCollection<Base> {
    // Here I will have methods and properties that relate to my application.
}

But I am prompted that I need to implement all of the following:

override val size: Int
override fun contains(element: Base): Boolean
override fun containsAll(elements: Collection<Base>): Boolean
override fun isEmpty(): Boolean
override fun add(element: Base): Boolean
override fun addAll(elements: Collection<Base>): Boolean
override fun clear()
override fun iterator(): MutableIterator<Base>
override fun remove(element: Base): Boolean
override fun removeAll(elements: Collection<Base>): Boolean
override fun retainAll(elements: Collection<Base>): Boolean

Do I actually need to implement all of these or am I going about this the wrong way? Aren’t these methods/properties already implemented and available when one accesses a MutableCollection class?

I’m new to Kotline and I have a very basic understanding of interfaces, so I might just be understanding this incorrectly; if that’s the case, please let me know.


#2

Why do you need your ow implementation of collection, why not use, say, ArrayList<Base>?


#3

Or maybe you want to use delegation instead of inheritance. Do you actually need to extend collection in your use case?


#4

Finally take a look to the core classes

http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-abstract-mutable-collection/index.html


#5

This seems to solve my problem. Thank you!


#6

At this point in the project, I’m not sure how many of the base methods/properties I would need. So my intention was to have access to all of them for the time being. The idea of delegation is definitely something I’ll keep in mind though!