Search code examples
scalaeta-expansion

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?


Solution

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