In Scala, the pattern matching anonymous function keeps surprising me. I just discovered the following behaviors, and I wanna know how to understand it.
It seems, the parameter signature of the anonymous function { case (a, b) => (b, a) } can be annotated both as a single tuple parameter and a tuple of parameters:
scala> ({ case (a, b) => (b, a) }: ((Int, Int)) => (Int, Int))
val res1: ((Int, Int)) => (Int, Int) = $Lambda$1160/0x0000000801127040@689fe2a3
scala> ({ case (a, b) => (b, a) }: (Int, Int) => (Int, Int))
val res2: (Int, Int) => (Int, Int) = $Lambda$1161/0x000000080106e840@1784d711
Notice res1 has a tuple parameter, while res2 has two parameters. Why is that? Is this behavior defined in language specs? (Sorry didn't check out yet, it seems too dense for me at the moment.)
Also, the res1 function magically accepts both a tuple argument and two arguments at call-site.
scala> res1((1,2))
val res3: (Int, Int) = (2,1)
scala> res1(1,2)
val res4: (Int, Int) = (2,1)
In comparison, res2 won't accept a tuple argment:
scala> res2((1,2))
^
error: not enough arguments for method apply: (v1: Int, v2: Int): (Int, Int) in trait Function2.
Unspecified value parameter v2.
What's going on here? Why res1 can change its signature as it sees fit?