https://kotlinlang.org logo
#stdlib
Title
m

mbonnin

06/22/2022, 3:24 PM
I'm confused by the
SuspiciousCollectionReassignment
inspection. The description says:
Copy code
fun test() {
      var list = listOf(0)
      list += 42 // new list is created, variable 'list' still contains only '0'
  }
But doing the same thing in playground yields
[0, 42]
. What am I missing?
p

Paul Griffith

06/22/2022, 3:27 PM
The wording is a bit confusing, but the reason it’s “suspicious” is that the
+=
operator is quietly allocating an entire new collection
m

mbonnin

06/22/2022, 3:28 PM
Yea but sometimes you have no control over this
Typically Gradle
var
properties
p

Paul Griffith

06/22/2022, 3:29 PM
🤷 it’s “suspicious”, not “wrong”
m

mbonnin

06/22/2022, 3:29 PM
Yup
p

Paul Griffith

06/22/2022, 3:31 PM
I think the preferred way to work around (rather than a suppress warnings) would be to make it explicit you’re setting to a new list, e.g.
list = list + 42
👍 1
but there’s also nothing stopping you from suppressing and moving on 🙂
m

mbonnin

06/22/2022, 3:32 PM
I've been suppressing this one for years, don't know why I decided to investigate more today 🙂
K 1
That clears it up, thanks!
👍 1
n

nkiesel

06/22/2022, 8:07 PM
One reason I can see for "suspicious" is that
var l1 = listOf(0); var l2 = l1; l1 += 42
results in "l2=[0]", but a
var l1 = mutableListOf(0); var l2 = l1; l1 += 42
results in "l2=[0,42]"
m

mbonnin

06/22/2022, 8:09 PM
It behaves exactly like int:
var l1 = 0; var l2 = l1; l1 += 42
results in "l2==0" so I'd argue this is behaving as expected
I think the issue is with performance, not behaviour
n

nkiesel

06/22/2022, 8:11 PM
the "MutableList" case behaves differently.
m

mbonnin

06/22/2022, 8:12 PM
Ooo right, I see it now
The fact that
l1 += 42
is not the same as
l1 = l1 + 42
in the mutable case feels weird
m

mcpiroman

06/22/2022, 8:44 PM
IMO this introspection could trigger just on
+=
with `var MutableList`but no with `var List`nor
val MutableList
.
plus one 1
3 Views