开发者

Modifying multiple Lists inside a function and returning it in Scala

开发者 https://www.devze.com 2023-01-16 21:35 出处:网络
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:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消