In Scala, how do I perform additional string manipulation when using foreach on a List?
For example to print everything I can do
list.foreach(println(_))
How would I do the equivalent of
list.foreach(prin开发者_高级运维tln(_ + "mystring"))
In order to fix your second example you can name function argument like this:
list.foreach(x => println(x + "mystring"))
By the way, as alternative you can at first map
your list and then print each element in it:
list map (_ + "mystring") foreach println
This will produce the same results.
Just a bit of additional information to other two answers:
list.foreach(println(_))
is basically short forlist.foreach(s => println(s))
.list.foreach(println(_ + "mystring"))
is syntactically correct, but it is equivalent tolist.foreach(println(s => s + "mystring"))
(and the compiler can't figure out what the type ofs
is) instead of what you want.
You can either declare a variable:
list.foreach(s => println(s + "mystring"))
or you can declare a method that does what you want, and then call that:
def myprint(s: String) = println(s + "mystring"))
list.foreach(myprint)
精彩评论