How to add an item to an ArrayList in Kotlin?
Solution 1:
For people just migrating from java
, In Kotlin
List
is by default immutable and mutable version of Lists is called MutableList
.
Hence if you have something like :
val list: List<String> = ArrayList()
In this case you will not get an add()
method as list is immutable. Hence you will have to declare a MutableList
as shown below :
val list: MutableList<String> = ArrayList()
Now you will see an add()
method and you can add elements to any list.
Solution 2:
If you have a MUTABLE collection:
val list = mutableListOf(1, 2, 3)
list += 4
If you have an IMMUTABLE collection:
var list = listOf(1, 2, 3)
list += 4
note that I use val
for the mutable list to emphasize that the object is always the same, but its content changes.
In case of the immutable list, you have to make it var
. A new object is created by the +=
operator with the additional value.