icevur.blogg.se

Kotlin list any example
Kotlin list any example












kotlin list any example

Why? As above, the type you’ve declared the list as (rather than the implementation itself) is the determining factor in what += will actually do when you use it.

kotlin list any example

Calling += adds the element to existing list.Calling += copies the whole list into a new list.Under the hood, in each case above we are dealing with ArrayLists.

kotlin list any example

option 1 var list : List = ArrayList () list += 1 // option 2 var list : List = mutableListOf () list += 1 // option 3 val list = mutableListOf () list += 1 One way we can do that is to reassign the original list var to the new list which is returned each time (note because we are reassigning the variable, we need to switch from val to var): To fix this, we need to stop ignoring the returned list. We call foo + 2 and are given another new list back, which we ignore again. When we call foo + 1 we are given a new list back that we ignore. So this now explains why, in our original example, we were left looking at an empty list. Here’s the important thing to remember: it doesn’t modify the original list.

  • adds all elements from the original list to it.
  • Note the signature of this function: it has operator in the signature and is called plus - this is why it is invoked when you call foo + 1. * Returns a list containing all elements of the original collection and then the given.














    Kotlin list any example