RemoveAt not found in list kotlin?

Viewed 916

I have a list whose value is filled from API

var dataList: List<Data?>? = null

I need to remove the element from 0th index

while in java I could use

dataList.removeAt(0)

But I don't see the function in kotlin

3 Answers

List supports only read-only access while MutableList supports adding and removing elements.

so var dataList: MutableList<Data?>? = null will give you the option to remove an element.

This is because unlike java List is immutable in Kotlin. That means you can't modify after declaring it. To get functionalities like add,remove you can declare a mutable list in Kotlin like this:

val mutableList = mutableListOf<String>()
mutableList.add("Some data")
mutableList.removeAt(0)

You can't remove an item from a List. Nor can you add an item, nor change one. That's because List is a read-only interface!

If the list is mutable, you could instead have a MutableList reference to it. MutableList is a subinterface that adds all the methods for adding, changing, and removing items.

Related