Reputation: 44051
For example to print everything I can do
list.foreach(println(_))
How would I do the equivalent of
list.foreach(println(_ + "mystring"))
Upvotes: 2
Views: 849
Reputation: 170745
Just a bit of additional information to other two answers:
list.foreach(println(_))
is basically short for list.foreach(s => println(s))
.
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.
Upvotes: 4
Reputation: 167891
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)
Upvotes: 3
Reputation: 26566
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.
Upvotes: 9