mbonnin

    mbonnin

    3 months ago
    I'm confused by the
    SuspiciousCollectionReassignment
    inspection. The description says:
    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

    3 months ago
    The wording is a bit confusing, but the reason it’s “suspicious” is that the
    +=
    operator is quietly allocating an entire new collection
    mbonnin

    mbonnin

    3 months ago
    Yea but sometimes you have no control over this
    Typically Gradle
    var
    properties
    p

    Paul Griffith

    3 months ago
    🤷 it’s “suspicious”, not “wrong”
    mbonnin

    mbonnin

    3 months ago
    Yup
    p

    Paul Griffith

    3 months ago
    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
    but there’s also nothing stopping you from suppressing and moving on 🙂
    mbonnin

    mbonnin

    3 months ago
    I've been suppressing this one for years, don't know why I decided to investigate more today 🙂
    That clears it up, thanks!
    n

    nkiesel

    3 months ago
    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]"
    mbonnin

    mbonnin

    3 months ago
    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

    3 months ago
    the "MutableList" case behaves differently.
    mbonnin

    mbonnin

    3 months ago
    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
    mcpiroman

    mcpiroman

    3 months ago
    IMO this introspection could trigger just on
    +=
    with var MutableListbut no with var Listnor
    val MutableList
    .