Is there a cleaner way to pattern-match in Scala anonymous functions?
Solution 1:
Believe it or not, this works:
val b = List(1, 2)
b map {
case 1 => "one"
case 2 => "two"
}
You can skip the p => p match
in simple cases. So this should work:
val c = a map {
case ((x,y) -> u) => (y,x) -> u
}
Solution 2:
In your example, there are three subtly different semantics that you may be going for.
-
Map over the collection, transforming each element that matches a pattern. Throw an exception if any element does not match. These semantics are achieved with
val b = a map { case ((x, y), u) => ((y, x), u) }
-
Map over the collection, transforming each element that matches a pattern. Silently discard elements that do not match:
val b = a collect { case ((x, y), u) => ((y, x), u) }
-
Map over the collection, safely destructuring and then transforming each element. These are the semantics that I would expect for an expression like
val b = a map (((x, y), u) => ((y, x), u)))
Unfortunately, there is no concise syntax to achieve these semantics in Scala. Instead, you have to destructure yourself:
val b = a map { p => ((p._1._2, p._1._1), p._2) }
One might be tempted to use a value definition for destructuring:
val b = a map { p => val ((x,y), u) = p; ((y, x), u) }
However, this version is no more safe than the one that uses explicit pattern matching. For this reason, if you want the safe destructuring semantics, the most concise solution is to explicitly type your collection to prevent unintended widening and use explicit pattern matching:
val a: List[((Int, Int), Int)] = // ... // ... val b = a map { case ((x, y), u) => ((y, x), u) }
If
a
's definition appears far from its use (e.g. in a separate compilation unit), you can minimize the risk by ascribing its type in the map call:val b = (a: List[((Int, Int), Int)]) map { case ((x, y), u) => ((y, x), u) }
Solution 3:
In your quoted example, the cleanest solution is:
val xs = List((1,2)->3,(4,5)->6,(7,8)->9)
xs map { case (a,b) => (a.swap, b) }
Solution 4:
val b = a map { case ((x,y), u) => ((y,x), u) }