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值?
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."
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |