From Programming in Scala,we know that foreach is a high-order function which takes a procedure with return type Unit.So I think the following slice would work:
val abcde = List("a","b","c","d","e")
abcde.foreach(print _.toUpperCase)
however it tells me that:
1: error: ')' expected but '.' found.
abcde foreach (println _.toUpperCase)
^
But these two below both work well:
println("abcde".toUpperCase)
abcde.foreach(print _)
So what’s the difference?
These two are using
_in different ways:In the first case, you have an anonymous function where
_denotes a placeholder for a parameter.In the second case,
_means you’d like a function value for the methodprint(an eta expansion).So comparing the two is irrelevant.
More to the point would be this:
As you can see, this doesn’t work, so replacing
"abcde"with_wouldn’t work either.