Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between foreach(println) and foreach(println())?

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?

like image 336
Julia Chang Avatar asked Dec 06 '25 08:12

Julia Chang


1 Answers

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."

like image 152
jwvh Avatar answered Dec 08 '25 21:12

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!