views:

116

answers:

1

I have a List of type [T] and [B] in scala, with an object e of type E.

I want to make a function that accepts those three parameters:

def doSomething(t : List[T], b List[B], e : E) {
 ... }

However I realise that List is immutable, and anything passed to a function is considered as val (not var). But I need to modify t and b and return the modifications back to the caller of the function. Does anyone have any idea how to do this?

I can't go and change the list to array... Because I've been using it everywhere and the file is so big..

+13  A: 

You should modify t and b in a functional way using higher order functions like map, filter,... and put the result of them into new vals (e.g. modifiedT, modifiedB). Then you can use a Tuple2 to return 2 values from the method.

def doSomething(t: List[T], b: List[B], e: E) = {
  // somehting you want to do
  val modifiedT = t.map(...).filter(...)
  val modifiedB = b.map(...).filter(...)
  (modifiedT, modifiedB) // returns a Tuple2[List[T], List[B]]
}

In the calling method you can then assign the values this way:

val (t2, b2) = doSomething(t, b, e)

Of course it depends on what you mean with "modify". If this modification is complicated stuff you should consider using view to make calculation lazy to move the time of calculation to a later point in time.

michael.kebe
You need an `=` between `e: E)` and `{` if you're going to return something.
Rex Kerr
You are correct Rex, thanks. I don't know how often I forget this small `=` in Scala...
michael.kebe
Thank you, it works really well michael!
the_great_monkey