Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit MutableList in Kotlin?

Tags:

kotlin

I am trying to inherit MutableList, and add my own function to it. For example:

class CompositeJob : MutableList<Job> {
    fun cancelAllJobs() {
        for (job in this) {
            job.cancel()
        }
    }
}

But I got the following error:

Class 'CompositeJob' is not abstract and does not implement abstract member
public abstract val size: Int defined in kotlin.collections.MutableList

How can I inherit MutableList, so I can use its original methods like add() and isEmpty(), and add my own one?

Thanks.

like image 229
iForests Avatar asked Jul 06 '18 05:07

iForests


2 Answers

One option other answers don't mention is delegation:

class CompositeJob : MutableList<Job> by mutableListOf() {
    fun cancelAllJobs() {
        for (job in this) {
            job.cancel()
        }
    }
}

is basically equivalent to

class CompositeJob : MutableList<Job> {
    private val impl: MutableList<Job> = mutableListOf()
    override fun size() = impl.size()
    override fun add(x: Job) { impl.add(x) }
    // etc for all other MutableList methods

    fun cancelAllJobs() {
        for (job in this) {
            job.cancel()
        }
    }
}
like image 125
Alexey Romanov Avatar answered Sep 23 '22 14:09

Alexey Romanov


MutableList is an interface - it doesn't implement any of its methods, just declares them. If you want to implement MutableList from scratch, you'll have to implement all 20 of its methods plus the size property, as your error already told you.

You can, however, subclass actual implementations of this interface, for example ArrayList or LinkedList:

class CompositeJob : ArrayList<Job>() {
    fun cancelAllJobs() {
        for (job in this) {
            job.cancel()
        }
    }
}

Edit: If you're just looking to group coroutine Job instances, you should use a parent Job, a SupervisorJob, and CoroutineScope at this point, instead of collecting jobs like this manually.

like image 40
zsmb13 Avatar answered Sep 24 '22 14:09

zsmb13