2

So, I have a simple collection, say:

val a = List(1, 2, 3, 4)

I want to map it to a list of tuples, and then filter over that, and then later map over the result of it, so it would be something like:

a.map(x => (x, x * x)).filter(tup => tup._2 < 10).map(tup => tup._1 + tup._2)

Except instead of using tup and tup._1, I want to use variable names like number and square, preferably in the arguments section.

Is it possible? How can I achieve that?

4

1 回答 1

9

考虑使用偏函数和收集函数:

scala> val a = List(1, 2, 3, 4)
a: List[Int] = List(1, 2, 3, 4)

scala> a.map(x => (x, x * x)) collect {
     |   case (number, square) if square < 10 =>
     |     number + square
     | }
res0: List[Int] = List(2, 6, 12)

在这种情况下,收集就像地图和过滤器的组合一样

于 2013-10-18T19:05:31.823 回答