Home > Software design >  Kotlin - Do kotlin list filter creates a new list object?
Kotlin - Do kotlin list filter creates a new list object?

Time:05-21

fun main() {
  var list1 = listOf("AAAA", "ASAS", "ADDAD", "AS")
  var list2 = list1
  println(list2 === list1)
  list2 = list2
    .filter { it.length >= 3 }
  println(list2 === list1)
}

The output of above code is:

true
false

But I am confused why list1 is not being modified since both list1 and list2 are referencing to same list object first. Can anyone please help me understand what exactly is going on here?

CodePudding user response:

Indeed, filter does create a new list.

And when you do

list2 = list2
    .filter { it.length >= 3 }

you are assigning that new list to list2, so now list2 stops referring to what list1 refers to, and starts to refer to the list that was created by filter instead. Therefore, list2 and list1 now refers to different things.

  • Related