开发者

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:

  1. list.foreach(println(_)) is basically short for list.foreach(s => println(s)).

  2. list.foreach(println(_ + "mystring")) is syntactically correct, but it is equivalent to list.foreach(println(s => s + "mystring")) (and the compiler can't figure out what the type of s 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜