3

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

daniu
  • 14,137
  • 4
  • 32
  • 53
WISHY
  • 11,067
  • 25
  • 105
  • 197

3 Answers3

4

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.

Ben Shmuel
  • 1,819
  • 1
  • 11
  • 20
2

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)
Alif Hasnain
  • 1,176
  • 1
  • 11
  • 24
1

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.

gidds
  • 16,558
  • 2
  • 19
  • 26