Is there a cleaner way to pattern-match in Scala anonymous functions?

Owen picture Owen · Jun 23, 2011 · Viewed 28.3k times · Source

I find myself writing code like the following:

val b = a map (entry =>
    entry match {
        case ((x,y), u) => ((y,x), u)
    }
)

I would like to write it differently, if only this worked:

val c = a map (((x,y) -> u) =>
    (y,x) -> u
)

Is there any way I can get something close to this?

Answer

sblundy picture sblundy · Jun 23, 2011

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
}