deltanovember
deltanovember

Reputation: 44051

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(println(_ + "mystring"))

Upvotes: 2

Views: 849

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170745

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.

Upvotes: 4

Rex Kerr
Rex Kerr

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

tenshi
tenshi

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

Related Questions