``` var immutableList = listOf(1, 2, 3) immutable...
# getting-started
h
Copy code
var immutableList = listOf(1, 2, 3)

immutableList += 4
Since
plusAssign
operator is not defined on a
Collection
in Kotlin, what does
immutableList += 4
really do. It can't add the element to the the
List
as it is immutable unlike
ArrayList
. So does it first create a new
List
from the
plus
operator and then assign it to the reference variable through
=
?
r
Yes, this one does not use operator overloading, so it is interpreted literally as
Copy code
immutableList = immutableList + 4
Note that if this was a mutable list, you'd get an error from ambiguity.
h
yep because both
mutableList = mutableList + 4
and
mutableList.plusAssign(4)
would be applicable in this case and hence compiler will generate an error for the ambiguity
right?
r
Exactly
👍 1
k
It does still use operator overloading of course 😉
h
@karelpeeters you are referring to the
+
in immutable list example right?
k
Yes.
h
Also if there was no
plus
operator defined on
List
, we would never get compiler error in the case of mutable list for
+=
right?
k
Yep.
r
@karelpeeters Fair point 🙂