scala 为什么我会在一种情况下而不是另一种情况下得到“缺少扩展函数的参数”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4701761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:43:50  来源:igfitidea点击:

Why do I get a "missing parameter for expanded function" in one case and not the other?

scala

提问by ebruchez

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) => x.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 ;)

我相信有一个合理的解释;)

回答by Francois G

This has already been addressed in a related question. Underscores extend outwards to the closest closing Expr: top-level expressions or expressions in parentheses.

这已经在相关问题中得到解决。下划线向外延伸到最接近的结尾Expr:顶级表达式或括号中的表达式。

(_.toString)is an expression in parentheses. The argument you are passing to Exceptionin the error case is therefore, after expansion, the full anonymous function (x$1) => x$1.toStringof type A <: Any => String, while Exceptionexpects a String.

(_.toString)是括号中的表达式。Exception因此,您在错误情况下传递给的参数是,在扩展之后,(x$1) => x$1.toStringtype的完整匿名函数A <: Any => String,而Exception期望 a String

In the printlncase, _by itself isn't of syntactic category Expr, but (println (_))is, so you get the expected (x$0) => println(x$0).

在这种println情况下,_本身不是语法 category Expr,而是(println (_)),所以你得到了预期的(x$0) => println(x$0).

回答by Daniel C. Sobral

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

部分应用函数

Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))

translates into

翻译成

Seq(fromDir, toDir) find (!_.isDirectory) foreach ((x) => println(x))

Anonymous Function Parameter

匿名函数参数

Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))

translates into

翻译成

Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception((x) => x.toString))