This article explores different ways to clear a mutable list in Kotlin.

1. Using clear() function

The standard operation to empty a list is using the clear() function, which efficiently removes all elements from it. This is the best approach in terms of performance. Note that this doesn’t work on unmodifiable lists.

Download Code

2. Using removeAll() function

We can also use the removeAll() function to remove all elements from a mutable list, that matches with any of the elements in the specified input. A typical invocation for this method would look like below to clear a list:

Download Code

3. Using remove() function

The idea is to get a copy of elements in the list and call the remove() function for each element. The copy of the list is used to avoid ConcurrentModificationException, since concurrent modification of the list is not allowed while iterating over it.

Download Code

4. Using Iterator.remove() function

The iterator’s remove() function doesn’t throw ConcurrentModificationException when some thread modifies the collection while another thread is iterating over it. It can be used as follows:

Download Code

That’s all about clearing a mutable list in Kotlin.