Scala 意外无法确定扩展函数的类型 [英] Scala unexpectedly not being able to ascertain type for expanded function
问题描述
为什么,在 Scala 中,给出:
Why, in Scala, given:
a = List(1, 2, 3, 4)
def f(x : String) = { x }
确实
a.map(_.toString)
工作,但是
a.map(f(_.toString))
给出错误
missing parameter type for expanded function ((x$1) => x$1.toString)
推荐答案
嗯... f()
接受一个字符串作为参数.构造 _.toString
具有类型 A <: Any =>字符串
.函数 f()
需要 String
的类型,所以上面的例子没有类型检查.在这种情况下,Scala 似乎很友好,并给了用户另一个机会.错误消息的意思是:根据我的类型推断算法,这不会编译.如果我无法推断,请将类型放入其中,它可能会."
Well... f()
takes a String as a parameter. The construct _.toString
has type A <: Any => String
. The function f()
expects a type of String
, so the example above does not type check. It seems that Scala is friendly in this case and gives the user another chance. The error message means: "By my type inference algorithms this does not compile. Put the types in and it might, if it's something I can't infer."
在这种情况下,您必须直接编写匿名函数,即 a.map(n => f(n.toString))
.这不是类型推断的限制,而是通配符的限制.基本上,当您编写 a.map(f(_.toString))
时,_.toString
会扩展为它可以找到的最接近括号内的匿名函数,否则这将导致极大的歧义.想象一下类似 f(g(_.toString))
的东西.这意味着 f(g(x => x.toString))
还是 f(x => g(x.toString))
?多个嵌套函数调用会出现更严重的歧义.因此,Scala 类型检查器采用了最合乎逻辑的解决方案,如上所述.
You would have to write the anonymous function longhand in this case, i.e. a.map(n => f(n.toString))
. This is not a limitation of type inference, but of the wildcard symbol. Basically, when you write a.map(f(_.toString))
, the _.toString
gets expanded into an anonymous function inside the closest brackets it can find, otherwise this would lead to enormous ambiguity. Imagine something like f(g(_.toString))
. Does this mean f(g(x => x.toString))
or f(x => g(x.toString))
? Worse ambiguities would arise for multiple nested function calls. The Scala type checker therefore takes the most logical solution, as described above.
Nitpick:你的代码的第一行应该是 val a = List(1,2,3,4)
:).
Nitpick: the first line of your code should be val a = List(1,2,3,4)
:).
这篇关于Scala 意外无法确定扩展函数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!