Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
937 views
in Technique[技术] by (71.8m points)

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

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 ;)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 to Exception in the error case is therefore, after expansion, the full anonymous function (x$1) => x$1.toString of type A <: Any => String, while Exception expects a String.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...