kotlinmutablelist

Kotlin Array, List, MutableList .plus() not working


Where am I wrong ?

I use plus() function for adding in end of MutableList Element or List, but its not working. I may use Add() but I spent a lot of time trying understand my bad.

fun main() {
    var arr=mutableListOf<Int>(4,5) ;
    var arr2=mutableListOf<Int>(1,3); 
    arr.add(8);
    arr2.plus(arr)
     
    println( arr2.size);
}

Result: 2

fun main() {
    var arr=mutableListOf<Int>(4,5) ;
    var arr2=mutableListOf<Int>(1,3); 
    arr.add(8);
    arr2.plus(arr)
     
    println( arr2.size);
}

Result: 2

With Array and List the same.

From Kotlin Docs


Solution

  • Kotlin has two different operators for adding to a list:

    plus (+), which returns a new list containing the original list and the added element or list, and
    plusAssign (+=), which adds the given element or list to the original list.

    So, the correct way to do this would be:

    var arr = mutableListOf<Int>(4,5)
    var arr2 = mutableListOf<Int>(1,3)
    arr += 8 // or arr.plusAssign(8)
    arr2 += arr2 // or arr.plusAssign(arr2)
     
    println(arr)