Sayat Stb - 1 year ago 130

Scala Question

I've a question regarding this pattern matching in scala:

`val div: (Double, Double) => Double = {`

case (x, y) if y != 0 => x / y

}

I've understand how pattern matching works and its syntaxis in scala, but this expression drives me crazy. How does complier knows that x and y is an arguments of the function and pattern match on them?

Answer Source

The rules for this are defined in section 8.5 "Pattern Matching Anonymous Functions" of the Scala Language Specification. If using an anonymous function with pattern matching, the type must be partially provided. You do that by saying the type is `(Double, Double) => Double`

, which is shorthand for `Function2[Double, Double, Double]`

.

Now:

If the expected type is

`scala.Function`

, the expression is taken to be equivalent to the anonymous function:k[S,…,_{1}S,_{k}R](x:_{1}S,…,_{1}x:_{k}S) => (_{k}x,…,_{1}x) match { case p_{k}_{1}=> b_{1}… case p_{n}=> b_{n}}

So no matter what the arity of your function, the pattern match is passed a tuple of the function's arguments, hence you can use the regular tuple extractor syntax.

So your example is short for

```
val div: (Double, Double) => Double = (a, b) => (a, b) match {
case (x, y) if y != 0 => x / y
}
```

or

```
val div = (a: Double, b: Double) => (a, b) match {
case (x, y) if y != 0 => x / y
}
```

The *naming* of the extractor parameters `x`

and `y`

is up to your imagination. You decide how to call the resulting elements of the extractor, you could as well write `case (foo, bar) => ...`