How to add an item to an ArrayList in Kotlin?

Ramesh picture Ramesh · Sep 15, 2017 · Viewed 120k times · Source

How to add an item to an ArrayList in Kotlin?

Answer

Tarun picture Tarun · Jun 17, 2018

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.