Type inference failing on a `Function2` argument u

2020-04-16 06:16发布

问题:

Why does the type inferencer give up on this:

def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_ + _) / 2)   // no

Like so:

<console>:35: error: missing parameter type for expanded function 
              ((x$1, x$2) => x$1.$plus(x$2))
       def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_ + _) / 2)
                                                               ^

This is a strange subtlety which seems to have to do with the parentheses. For example, without using infix syntax it works:

def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map(_.+(_) / 2)   // yes

If I add another pair of parentheses for the fun of it, it fails again:

def test(a: Seq[Int], b: Seq[Int]) = (a, b).zipped.map((_.+(_)) / 2)   // no

回答1:

I don't remember where in SLS it is written, but lambda desugares to the closest scope. Map expects a function (Int, Int) => B, so when you write map(_.+(_) / 2) it is desugared into what is expected. But in the case of ((_ + _) / 2) or ((_.+(_)) / 2) your lambda is desugared into (((x, y) => x + y) / 2), basically you're trying to devise a function by 2 and that's why Scalac can't infer types