Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Scala pattern matching syntax

I had a List of Scala tuples like the following:

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

and I wanted to map it in a list of Int where each item is the sum of the Ints in a the corresponding tuple. I also didn't want to use to use the x._1 notation so I solved the problem with a pattern matching like this

def addTuple(t: (Int, Int)) : Int = t match { 
    case (first, second) => first + second 
}
var r = l map addTuple

Doing that I obtained the list r: List[Int] = List(3, 5, 7) as expected. At this point, almost by accident, I discovered that I can achieve the same result with an abbreviated form like the following:

val r = l map {case(first, second) => first + second}

I cannot find any reference to this syntax in the documentation I have. Is that normal? Am I missing something trivial?

like image 324
Mario Fusco Avatar asked Sep 16 '10 21:09

Mario Fusco


People also ask

How does Scala pattern matching work?

Pattern matching allows matching any sort of data with the first match policy. Each case statement returns a value, and the whole match statement is virtually a function that returns a matched value. Multiple values can be tested in a single line by using “|“.

Does Scala have pattern matching?

Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.

What does _* mean in Scala?

: _* is a special instance of type ascription which tells the compiler to treat a single argument of a sequence type as a variable argument sequence, i.e. varargs. It is completely valid to create a Queue using Queue.

What is the default option in a match case in Scala?

getList("instance").


1 Answers

See Section 8.5 of the language reference, "Pattern Matching Anonymous Functions".

An anonymous function can be defined by a sequence of cases

{case p1 =>b1 ... case pn => bn }

which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1, ..., Sk, R] for some k > 0, or scala.PartialFunction[S1, R], where the argument type(s) S1, ..., Sk must be fully determined, but the result type R may be undetermined.

The expected type deternines whether this is translated to a FunctionN or PartialFunction.

scala> {case x => x}  
<console>:6: error: missing parameter type for expanded function ((x0$1) => x0$1 match {
  case (x @ _) => x
})
       {case x => x}
       ^

scala> {case x => x}: (Int => Int)
res1: (Int) => Int = <function1>

scala> {case x => x}: PartialFunction[Int, Int]
res2: PartialFunction[Int,Int] = <function1>
like image 108
retronym Avatar answered Sep 19 '22 18:09

retronym