1
votes

Snippet 1:

val l = List(1,2,43,4)
l.map(i => i *2)

Snippet 2:

val s = "dsadadaqer12"
val g = s.groupBy(c=>c)
g.map  ( {case (c,s) => (c,s.length)})

In snippet #2, the syntax different than #1 , i.e. curly braces required -- why? I thought the following would compile, but it does not:

g.map ( (c,s) => (c,s.length))

Can someone explain why?

Thanks

2

2 Answers

4
votes

The difference between the two is - the latter uses Pattern Matching and the former doesn't.

The syntax g.map({case (c,s) => (c,s.length)}) is just syntax sugar for:

g.map(v => v match { case (c,s) => (c,s.length) })

Which means: we name the input argument of our anonymous function v, and then in the function body we match it to a tuple (c,s). Since this is so useful, Scala provides the shorthand version you used.

Of course - this doesn't really have anything to do with whether you use a Map or a List - consider all the following possibilities:

scala> val l = List(1,2,43,4)
l: List[Int] = List(1, 2, 43, 4)

scala> l.map({ case i => i*2 })
res0: List[Int] = List(2, 4, 86, 8)

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

scala> l2.map({ case (i, j) => i*j })
res1: List[Int] = List(2, 12)

scala> val g = Map(1 -> 2, 3 -> 4)
g: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)

scala> g.map(t => t._1 * t._2)
res2: scala.collection.immutable.Iterable[Int] = List(2, 12)

Both Map and List can use both syntax options, depending mostly on what you actually want to do.

1
votes

1- g.map{case (c,s) => (c,s.length)}

2- g.map((c,s) => (c,s.length))

The map method pulls a single argument, a 2-tuple, from the g collection. The 1st example compiles because the case statement uses pattern matching to extract the tuple's elements whereas the 2nd example doesn't and it won't compile. For that you'd have to do something like: g.map(t => (t._1, t._2.length))

As for the parenthesis vs. curly braces: braces have always been required for "partial functions," which is what that case statement is. You can use either braces or parens for anonymous functions (i.e. x => ...) although you are required to use braces if the function is more than a single line (i.e. has a carriage-return).

I read somewhere that this parens/braces distinction might be relaxed but I don't know if that's going to happen any time soon.