Domanda

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
È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top