How to remove all items from ArrayList in kotlin

The List type in Kotlin is not mutable. If you want to cause your list to change, you need to declare it as a MutableList.

I would suggest changing this line:

var fromAutoCompleteArray: List<String> = ArrayList()

To this:

val fromAutoCompleteArray: MutableList<String> = mutableListOf()

And then you should be able to call any of these:

fromAutoCompleteArray.clear()     // <--- Removes all elements
fromAutoCompleteArray.removeAt(0) // <--- Removes the first element

I also recommend mutableListOf() over instantiating an ArrayList yourself. Kotlin has sensible defaults and it is a bit easier to read. It will end up doing the same thing either way for the most part.

It is also preferable to use val over var, whenever possible.

Update: Vals not vars, thanks for spotting that Alexey

Tags:

Android

Kotlin