scala - Why foreach fail with String typed List with toUpperCase? -
from programming in scala,we know foreach high-order function takes procedure return type unit.so think following slice work:
val abcde = list("a","b","c","d","e") abcde.foreach(print _.touppercase) however tells me that:
1: error: ')' expected '.' found. abcde foreach (println _.touppercase) ^ but these 2 below both work well:
println("abcde".touppercase) abcde.foreach(print _) so what's difference?
these 2 using _ in different ways:
abcde.foreach(print _.touppercase) abcde.foreach(print _) in first case, have anonymous function _ denotes placeholder parameter.
in second case, _ means you'd function value method print (an eta expansion).
so comparing 2 irrelevant.
more point this:
scala> print "abcde".touppercase <console>:1: error: ';' expected string literal found. print "abcde".touppercase ^ as can see, doesn't work, replacing "abcde" _ wouldn't work either.
Comments
Post a Comment