219

In Java we could do the following

public class TempClass {
    List<Integer> myList = null;
    void doSomething() {
        myList = new ArrayList<>();
        myList.add(10);
        myList.remove(10);
    }
}

But if we rewrite it to Kotlin directly as below

class TempClass {
    var myList: List<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        myList!!.add(10)
        myList!!.remove(10)
    }
}

I got the error of not finding add and remove function from my List

I work around casting it to ArrayList, but that is odd needing to cast it, while in Java casting is not required. And that defeats the purpose of having the abstract class List

class TempClass {
    var myList: List<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        (myList!! as ArrayList).add(10)
        (myList!! as ArrayList).remove(10)
    }
}

Is there a way for me to use List but not needing to cast it, like what could be done in Java?

Alex R
  • 10,320
  • 12
  • 76
  • 145
Elye
  • 30,821
  • 26
  • 115
  • 272
  • 1
    Just a comment to why you can't do `myList = null` and then later on call add without `!!`. You could overcome this by using the `lateinit` keyword in front of your property like so: `lateinit var myList: List` this way you won't need to initialise the list immediately, but you guarantee to the compiler that you will initialise it before using the list the first time. It's a smoother solution, but it puts a responsibility on you as a developer. – Darwind Aug 21 '18 at 11:03

10 Answers10

393

Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.

https://kotlinlang.org/docs/reference/collections.html

You'll need to use a MutableList list.

class TempClass {
    var myList: MutableList<Int> = mutableListOf<Int>()
    fun doSomething() {
        // myList = ArrayList<Int>() // initializer is redundant
        myList.add(10)
        myList.remove(10)
    }
}

MutableList<Int> = arrayListOf() should also work.

fulvio
  • 24,168
  • 20
  • 122
  • 198
41

Defining a List collection in Kotlin in different ways:

  • Immutable variable with immutable (read only) list:

    val users: List<User> = listOf( User("Tom", 32), User("John", 64) )
    


  • Immutable variable with mutable list:

    val users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
    

    or without initial value - empty list and without explicit variable type:

    val users = mutableListOf<User>()
    //or
    val users = ArrayList<User>()
    
    • you can add items to list:
      • users.add(anohterUser) or
      • users += anotherUser (under the hood it's users.add(anohterUser))


  • Mutable variable with immutable list:

    var users: List<User> = listOf( User("Tom", 32), User("John", 64) )
    

    or without initial value - empty list and without explicit variable type:

    var users = emptyList<User>()
    
    • NOTE: you can add* items to list:
      • users += anotherUser - *it creates new ArrayList and assigns it to users


  • Mutable variable with mutable list:

    var users: MutableList<User> = mutableListOf( User("Tom", 32), User("John", 64) )
    

    or without initial value - empty list and without explicit variable type:

    var users = emptyList<User>().toMutableList()
    //or
    var users = ArrayList<User>()
    
    • NOTE: you can add items to list:
      • users.add(anohterUser)
      • but not using users += anotherUser

        Error: Kotlin: Assignment operators ambiguity:
        public operator fun Collection.plus(element: String): List defined in kotlin.collections
        @InlineOnly public inline operator fun MutableCollection.plusAssign(element: String): Unit defined in kotlin.collections


see also: https://kotlinlang.org/docs/reference/collections.html

Lukas M.
  • 2,479
  • 17
  • 30
13

Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.

val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)

Or

val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)
dinesh salve
  • 167
  • 2
  • 5
8

Apparently, the default List of Kotlin is immutable. To have a List that could change, one should use MutableList as below

class TempClass {
    var myList: MutableList<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        myList!!.add(10)
        myList!!.remove(10)
    }
}

Updated Nonetheless, it is not recommended to use MutableList unless for a list that you really want to change. Refers to https://hackernoon.com/read-only-collection-in-kotlin-leads-to-better-coding-40cdfa4c6359 for how Read-only collection provides better coding.

Gastón Saillén
  • 9,076
  • 4
  • 39
  • 58
Elye
  • 30,821
  • 26
  • 115
  • 272
  • You're correct about using `MutableList`, however initializing it with `null` won't work. Only safe or non-null asserted calls are allowed on a nullable receiver of type `MutableList`. – fulvio Jun 20 '16 at 00:52
  • It works on my end, and no error found. I don't need to initialize it unless when I need it when `doSomething` – Elye Jun 20 '16 at 00:57
  • @Elye I know this is an old answer and question, but using `lateinit` instead of making the list nullable is the proper way of going about this issue. Don't remember whether `lateinit` was added from the beginning of Kotlin though, but this is definitely the solution nowadays to use it :-) – Darwind Aug 21 '18 at 11:05
7

In Kotlin you must use MutableList or ArrayList.

Let's see how the methods of MutableList work:

var listNumbers: MutableList<Int> = mutableListOf(10, 15, 20)
// Result: 10, 15, 20

listNumbers.add(1000)
// Result: 10, 15, 20, 1000

listNumbers.add(1, 250)
// Result: 10, 250, 15, 20, 1000

listNumbers.removeAt(0)
// Result: 250, 15, 20, 1000

listNumbers.remove(20)
// Result: 250, 15, 1000

for (i in listNumbers) { 
    println(i) 
}

Let's see how the methods of ArrayList work:

var arrayNumbers: ArrayList<Int> = arrayListOf(1, 2, 3, 4, 5)
// Result: 1, 2, 3, 4, 5

arrayNumbers.add(20)
// Result: 1, 2, 3, 4, 5, 20

arrayNumbers.remove(1)
// Result: 2, 3, 4, 5, 20

arrayNumbers.clear()
// Result: Empty

for (j in arrayNumbers) { 
    println(j) 
}
Andy Fedoroff
  • 26,838
  • 8
  • 85
  • 144
5

You can do with create new one like this.

var list1 = ArrayList<Int>()
var list2  = list1.toMutableList()
list2.add(item)

Now you can use list2, Thank you.

Dalvinder Singh
  • 987
  • 1
  • 10
  • 19
4

UPDATE: As of Kotlin 1.3.70, the exact buildList function below is available in the standard library as an experimental function, along with its analogues buildSet and buildMap. See https://blog.jetbrains.com/kotlin/2020/03/kotlin-1-3-70-released/.

Confining Mutability to Builders

The top answers here correctly speak to the difference in Kotlin between read-only List (NOTE: it's read-only, not "immutable"), and MutableList.

In general, one should strive to use read-only lists, however, mutability is still often useful at construction time, especially when dealing with third-party libraries with non-functional interfaces. For cases in which alternate construction techniques are not available, such as using listOf directly, or applying a functional construct like fold or reduce, a simple "builder function" construct like the following nicely produces a read-only list from a temporary mutable one:

val readonlyList = mutableListOf<...>().apply {
  // manipulate your list here using whatever logic you need
  // the `apply` function sets `this` to the `MutableList`
  add(foo1)
  addAll(foos)
  // etc.
}.toList()

and this can be nicely encapsulated into a re-usable inline utility function:

inline fun <T> buildList(block: MutableList<T>.() -> Unit) = 
  mutableListOf<T>().apply(block).toList()

which can be called like this:

val readonlyList = buildList<String> {
  add("foo")
  add("bar")
}

Now, all of the mutability is isolated to one block scope used for construction of the read-only list, and the rest of your code uses the read-only list that is output from the builder.

Raman
  • 13,024
  • 3
  • 72
  • 95
  • thanks and worked well with business logic within the apply method, even used anotherList.ForEach {add(foo)} inside the .appy{} – BENN1TH Aug 10 '19 at 02:10
3

https://kotlinlang.org/docs/reference/collections.html

According to above link List<E> is immutable in Kotlin. However this would work:

var list2 = ArrayList<String>()
list2.removeAt(1)
sgrover
  • 41
  • 4
  • That means that `list2` is a mutable list, see https://stackoverflow.com/questions/43114367/difference-between-arrayliststring-and-mutablelistofstring-in-kotlin. – CoolMind Dec 04 '18 at 16:00
2

A list is immutable by Default, you can use ArrayList instead. like this :

 val orders = arrayListOf<String>()

then you can add/delete items from this like below:

orders.add("Item 1")
orders.add("Item 2")

by default ArrayList is mutable so you can perform the operations on it.

Sachin
  • 3,815
  • 2
  • 13
  • 26
1

In concept of immutable data, maybe this is a better way:

class TempClass {
    val list: List<Int> by lazy {
        listOf<Int>()
    }
    fun doSomething() {
        list += 10
        list -= 10
    }
}
bbsimon
  • 229
  • 2
  • 2