Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying multiple Lists inside a function and returning it in Scala

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..

like image 703
Enrico Susatyo Avatar asked Sep 16 '10 07:09

Enrico Susatyo


1 Answers

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.

like image 109
michael.kebe Avatar answered Oct 04 '22 00:10

michael.kebe