Kotlin's List missing "add", "remove", Map missing "put", etc?

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.


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


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)