Sayat Stb Sayat Stb - 1 year ago 118
Scala Question

Pattern Matching Function Arguments

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?

0__ 0__
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].


If the expected type is scala.Function k [S1,…,Sk, R], the expression is taken to be equivalent to the anonymous function:

(x1:S1,…,xk:Sk) => (x1,…,xk) match {
  case p1 => b1 … case pn => bn

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


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) => ...