Passing parameters to mutator functions in Scala
题
I'm playing around in Scala to try and get the hang of it, so this code sample is simply academic.
I'm trying to pass a mutable List to a function, have that function perform work on it, and then after the function call I can use the updated list.
var data: List[Int] = List()
// Call to function to fill a list
data = initList(data)
// Output only 0-100
data.foreach( num => if (num < 100) { println(num) })
def initList(var data: List[Int]) : List[Int] = {
for ( i <- 0 to 1000 )
{
data = i :: data
}
data = data.reverse
data
}
The only code above that doesn't compile is the var
in def initList()
, and because data is then a val
I cannot perform any mutations to it within the function.
Let me start by saying that I know in Scala, mutators are usually frowned upon, so I'm not only open to a direct answer to my question, but open to better ways to do it entirely. Occasionally in projects there is a piece of data that goes from place to place to be updated, but if you cannot pass data to a function to be changed then what is a good alternative?
I've read through tutorials and google'd for this, I'm assuming I can't find much about it because it's not usually done this way in Scala.
没有正确的解决方案