Sai
Sai

Reputation: 15718

Difference between += and add to a MutableList in Kotlin

After looking at += to a mutableList, I could not figure out what it was immediately, my imagination was i = i+1 where i is an integer, which does not make sense in the below code, but after debugging I realized it was just adding an item to the list, so my question is what difference it makes to use += to add an item to list rather than just using mutableList.add(item), which is more readable at least in my case. Thank in advance.

musicSource.forEach { mediaItem ->
            val albumMediaId = mediaItem.album.urlEncoded
            val albumChildren = mediaIdToChildren[albumMediaId] ?: buildAlbumRoot(mediaItem)
            albumChildren += mediaItem
        }

Upvotes: 5

Views: 2241

Answers (3)

Yu Xiao
Yu Xiao

Reputation: 63

It's one of the operator overloading convention in Kotlin.

The compiler will translate expression like a += b to a.plusAssign(b) if type a implements the plusAssign operator function. It gives you power to write more expressive code.

Upvotes: 2

Ravindra Shekhawat
Ravindra Shekhawat

Reputation: 4353

  1. += for MutableList(in case you use), the compiler performs the following steps:

-If the function from the right column is available

  • If the corresponding binary function (i.e. plus() for plusAssign()) is available too, report error (ambiguity),

    • Make sure its return type is Unit, and report an error otherwise,

    • Generate code for a.plusAssign(b);

  • Otherwise, try to generate code for a = a + b (this includes a type check: the type of a + b must be a subtype of a).

  1. add function for MutableList :

return true if the element has been added, false if the collection does not support duplicates and the element is already contained in the collection.

Note : Please don't forget add() also have option to add element in specific index eg. add(index: Int, element: E)

Documentation

https://kotlinlang.org/docs/reference/operator-overloading.html#assignments

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/add.html

Upvotes: 2

user8959091
user8959091

Reputation:

There is no difference.
+= is an inline operator, and in MutableCollections.kt its implementation is:

@kotlin.internal.InlineOnly
public inline operator fun <T> MutableCollection<in T>.plusAssign(element: T) {
    this.add(element)
}

As you can see it uses the add() method.
You can use it or not. It's your choice.
This is more readable x = x + 1, but we tend to use x++.

Upvotes: 8

Related Questions