1

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
  • 12,131
  • 3
  • 23
  • 46
WISHY
  • 7,590
  • 21
  • 75
  • 142

3 Answers3

2

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,216
  • 1
  • 4
  • 14
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
  • 735
  • 1
  • 8
  • 18
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
  • 9,862
  • 1
  • 12
  • 16