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
.?!
Use mkString(sep: String)
function:
val names = List("Bob", "Fred", "Joe", "Julia", "Kim")
val x = names.mkString(" ") // "Bob Fred Joe Julia Kim"
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, eg,
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.