Rules for using the case argument to destroy a tuple in Scala

I have the following code:

val xs = List(('a', 1), ('a', 2), ('b', 3), ('b', 4)) 

I want to convert this to a map. e.g. Map('a' -> Seq(1,2), 'b' -> Seq(3,4)) . Therefore, I move on to the transformation record:

 xs.groupBy(_._1) map { case (k, v) => (k, v.map(_._2)) } 

Why the bracket after the card should be { . When I started, I suggested that I could do the following:

 xs.groupBy(_._1).map(case (k, v) => (k, v.map(_._2))) 

But this does not compile.

+7
source share
2 answers

It seems the real question here is when you can use a bracket ( instead of curly braces { to represent an anonymous function. I recommend taking a look at Daniel Sobral to answer the question: What is the formal difference in Scala between curly braces and brackets, and when should they be used?

+2
source

Because the .map method takes a function

What you actually written,

 map({ case (k, v) => (k, v.map(_._2)) }) 

and { case (k, v) => (k, v.map(_._2)) } is a short definition for an anonymous pattern matching function ( SLS , ยง8.5), which is one of the kinds of functions :

 val isOdd: PartialFunction[Int, String] = { case x if x % 2 == 1 => x+" is odd" } val upcastedIsOdd: Function[Int, String] = { case x if x % 2 == 1 => x+" is odd" } 

You cannot trim curly braces (so you lose the partial function and the matching patch), but you can skip the simple curly braces (and still save the partial function), as in the snippet below:

 scala> List(1,2,3).take(1) //res0: List[Int] = List(1) scala> List(1,2,3) take 1 //res1: List[Int] = List(1) 
+12
source

All Articles