为什么我在一个案例中获得"扩展函数的缺失参数"而不是另一个案例?

ebr*_*hez 22 scala

这种情况有效:

Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))
Run Code Online (Sandbox Code Playgroud)

然而,这不是:

Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))
Run Code Online (Sandbox Code Playgroud)

编译以此错误结束:

error: missing parameter type for expanded function ((x$4) => x$4.toString)
Run Code Online (Sandbox Code Playgroud)

现在,如果我这样写它再次编译:

Seq(fromDir, toDir) find (!_.isDirectory) foreach (s => throw new Exception(s.toString))
Run Code Online (Sandbox Code Playgroud)

我相信有合理的解释;)

hui*_*ker 28

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

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

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


Dan*_*ral 9

区别在于是_代表整个参数,还是表达式的一部分.根据具体情况,它属于以下两个类别之一:

部分应用功能

Seq(fromDir, toDir) find (!_.isDirectory) foreach (println(_))
Run Code Online (Sandbox Code Playgroud)

翻译成

Seq(fromDir, toDir) find (!_.isDirectory) foreach ((x$1) => println(x$1))
Run Code Online (Sandbox Code Playgroud)

匿名函数参数

Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception(_.toString))
Run Code Online (Sandbox Code Playgroud)

翻译成

Seq(fromDir, toDir) find (!_.isDirectory) foreach (throw new Exception((x$1) => x$1.toString))
Run Code Online (Sandbox Code Playgroud)