Valerin
Valerin

Reputation: 475

Scala - the return using a for() or foreach() in a list

How I can build a string (not to print it) from the returned value of a foreach or for statement applied in a List? Let say, I have this:

val names = List("Bob", "Fred", "Joe", "Julia", "Kim")
val x: String = for (name <- names) name //I don't need this println(name)

These name returned string I am trying to put in a String, connecting them by a space.?!

Upvotes: 1

Views: 360

Answers (2)

Dean Wampler
Dean Wampler

Reputation: 2151

for and foreach return Unit. They are only for side effects like printing. mkString is your best bet here, as Jean said. There's a second version that lets you pass in opening and closing strings, e.g.,

scala> names.mkString("[", ", ", "]") res0: String = [Bob, Fred, Joe, Julia, Kim]

If you need more flexibility, reduceLeft might be what you want. Here's what mkString is doing, more or less:

"[" + names.reduceLeft((str, name) => str + ", " + name) + "]"

One difference, though. reduceLeft throws an exception for an empty container, while mkString just returns "". foldLeft works for empty collections, but getting the delimiters right is tricky.

Upvotes: 2

Jean Logeart
Jean Logeart

Reputation: 53859

Use mkString(sep: String) function:

val names = List("Bob", "Fred", "Joe", "Julia", "Kim")
val x = names.mkString(" ")      // "Bob Fred Joe Julia Kim"

Upvotes: 4

Related Questions