Scala map of function using "_"
Why is it that (in the Scala REPL) I can write, for example,
def double(d: Int) = 2*d
(0 until 10).zipWithIndex.map(i => double(i._1))
or just
(0 until 10).zipWithIndex.map(_._1)
yet I can't write
(0 until 10).zipWithIndex.map(double(_._1))
error: missing parameter type for expanded function ((x$1) =&g开发者_如何学运维t; x$1._1) (0 until 10).zipWithIndex.map(double(_._1))
?
Scala tries to expand _._1
inside double
. So, it thinks you want to have
(0 until 10).zipWithIndex.map(double(i => i._1))
However, it also sees that i => i._1
does not really fit into one of double
’s argument types, so it complains and asks you to give a type hint to help the compiler. In this case, though, there cannot be a correct type definition, so the error message is kind of wrong there.
精彩评论