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
  • 13,079
  • 3
  • 28
  • 48
WISHY
  • 9,340
  • 22
  • 86
  • 156

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,549
  • 1
  • 8
  • 17
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
  • 944
  • 1
  • 9
  • 21
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
  • 13,337
  • 1
  • 17
  • 22