为什么我会收到“扩展函数缺少参数”的信息?在一种情况下而不是另一种情况下?
这种情况有效:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))
而这不起作用:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))
编译以这个错误结束:
error: missing parameter type for expanded function ((x$4) => x$4.toString)
现在如果我这样写它会再次编译:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (s => throw new Exception(s.toString))
我确信有一个合理的解释;)
Case this works:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))
Whereas this doesn't:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))
Compilation ends with this error:
error: missing parameter type for expanded function ((x$4) => x$4.toString)
Now if I write it this way it compiles again:
Seq(fromDir, toDir) find (!_.isDirectory) foreach (s => throw new Exception(s.toString))
I am sure there is a reasonable explanation ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
相关问题<中已经解决了这个问题< /a>.下划线向外延伸到最接近的结束
Expr
:顶级表达式或括号中的表达式。(_.toString)
是括号中的表达式。因此,在错误情况下传递给 Exception 的参数在扩展后是完整的匿名函数(x$1) => x$1.toString
类型为A <: Any =>; String
,而Exception
需要一个String
。在
println
情况下,_
本身不属于语法类别Expr
,而是(println (_))
是,所以你得到了预期的(x$0) =>; println(x$0)
.This has already been addressed in a related question. Underscores extend outwards to the closest closing
Expr
: top-level expressions or expressions in parentheses.(_.toString)
is an expression in parentheses. The argument you are passing toException
in the error case is therefore, after expansion, the full anonymous function(x$1) => x$1.toString
of typeA <: Any => String
, whileException
expects aString
.In the
println
case,_
by itself isn't of syntactic categoryExpr
, but(println (_))
is, so you get the expected(x$0) => println(x$0)
.区别在于
_
是代表整个参数,还是表达式的一部分。根据具体情况,它属于以下两个类别之一:部分应用函数
转换为
匿名函数参数
转换为
The difference is whether
_
stands for the whole parameter, or is part of an expression. Depending on which, it falls into one of the two following categories:Partially Applied Function
translates into
Anonymous Function Parameter
translates into