I have a string array:
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 => ?
Why does str.foreach(println) work with no problem, but str.foreach(println()) doesn't?
Isn't println equivalent to println() which returns a Unit value?
println is a method (convertible to a function) that takes input (String in this case) and produces a result (Unit) and a side-effect (printing to 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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With