Search code examples
listkotlinparameter-passingonclicklistener

Pass List <String> parameter by value instead of by reference


I have a code like this

val myFirstList = mutableListOf("Hello", "You can ", "edit, ", "run, ", "and share this code")
for (i in 0..myFirstList.size-2) {
    myFun(myFirstList)    
}

and a function like this

fun myFun (myList: MutableList<String>){
    myList.removeAt(0)
    println(myList)
 }

The output is:

[You can , edit, , run, , and share this code]

[edit, , run, , and > share this code]

[run, , and share this code]

[and share this code]

but I need it always (only 1st string removed):

[You can , edit, , run, , and share this code]

I found a workaround like this:

myFun(myFirstList.toList().toMutableList())   

but I'm sure there is a better solution to pass the list by value instead of by reference.

Thanks in advance for your answers


Solution

  • Speaking about the "passing a list by value": no, there isn't a better solution. What you call "passing by value" actually requires creating a full copy of the whole list. As such operation is pretty heavy on resources, it doesn't happen implicitly - we have to do it explicitly. You can skip toList() and keep only: myFirstList.toMutableList(), so we don't copy the data twice.

    However, speaking about your specific case, maybe there are better options than creating a copy, but it all depends on your needs. If you always only remove the first item, then maybe you should do it once, outside the myFun() and reuse the same, already cut list. You could also try: myList.subList(1, myList.size). It creates a view of the list, so it doesn't copy the data, but only wraps the original list. But again, it all depends on your specific case.