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 val
s (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.
精彩评论