Search code examples
kotlin

Difference between plus() vs add() in Kotlin List


I am new to Kotlin. I want to know the difference between plus() and add() in Kotlin List.


Solution

  • fun main() {
        val firstList = mutableListOf("a", "b")
        val anotherList = firstList.plus("c") // creates a new list and returns it. firstList is not changed
        println(firstList) // [a, b]
        println(anotherList) // [a, b, c]
    
        val isAdded = firstList.add("c") // adds c to the mutable variable firstList
        println(firstList) // [a, b, c]
        println(isAdded) // true
    
        val unmodifiableList = listOf("a", "b")
        val isAdded2 = unmodifiableList.add("c") // compile error, add is not defined on an UnmodifiableList
    }
    

    plus creates a new List out of an existing list and a given item or another list and returns the result (the new created List), while the input List is never changed. The item is not added to the existing List.

    add is only defined on modifiable Lists (while the default in Kotlin is an ImmutableList) and added the item to the existing List and returns true to indicate that the item was added successfully.