Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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

like image 722
Vinit Saxena Avatar asked Sep 03 '19 11:09

Vinit Saxena


3 Answers

Basically:

plus() adds element and returns the list containing this new value(s).

Returns a list containing all elements of the original collection and then the given [element].

So with plus():

val list1 = listOf(1,2,3)
val list2 = list1.plus(4) // [1, 2, 3, 4]
val list3 = listOf(0).plus(list2) // [0, 1, 2, 3, 4]

add() just adds an element and returns bool.

Adds the specified element to the end of this list. Return true because the list is always modified as the result of this operation.

like image 129
P.Juni Avatar answered Sep 25 '22 19:09

P.Juni


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.

like image 37
Simulant Avatar answered Sep 25 '22 19:09

Simulant


These two are completely different functions.

First of all add() can only add one item to mutable collection while plus() can add one item of a collection of items.

Second - add() function returns true or false depending on whether the collection was modified or not, while plus() returns result immutable collection.

The third and most important difference it that - the plus() function is a operator function overload which means that it is evaluated as static and can be used like this

val result = listOf(1,2,3) + 4 // [1,2,3,4]
val result2 = listOf(1,2,3).plus(4) // [1,2,3,4]
val result3 = listOf(1,2,3) + listOf(4,5,6) // [1, 2, 3, 4, 5, 6]
val result4 = listOf(1,2,3).plus(listOf(4,5,6)) // [1, 2, 3, 4, 5, 6]

While add() is just a regular instance function of MutableCollection interface

like image 23
Pavlo Ostasha Avatar answered Sep 23 '22 19:09

Pavlo Ostasha