foreach(println)和foreach(println())有什么区别?

Jul*_*ang 2 scala eta-expansion

我有一个字符串数组:

val str:Array[String] = Array("aa","bb")
scala> str.foreach(println) // works
aa
bb
scala> str.foreach(println()) // println() also returns a Unit, doesn't it?
                          ^
error: type mismatch;
found   : Unit
required: String => ?
Run Code Online (Sandbox Code Playgroud)

为什么str.foreach(println)没有问题,但没有问题str.foreach(println())
println等于println()哪个返回Unit值?

jwv*_*wvh 7

println是一种方法(可转换为函数),它接受输入(String在这种情况下)并产生结果(Unit)和副作用(打印到StdOut)。

println() is the invocation of a method that takes no input, produces a result (Unit), and a side-effect (\n to StdOut).

They aren't the same.

The 2nd one won't work in a foreach() because foreach() feeds elements (strings in this case) to its argument and println() won't take the input that foreach() is feeding it.

This will work str.foreach(_ => println()) because the underscore-arrow (_ =>) says: "Ignore the input. Just throw it away and invoke what follows."