Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala build up string from iterating over map

Tags:

scala

if i have a map and want to build up a string from iterating over it, is there a way to have the final string be a result of an expression instead of defining a variable and modifying that inside a loop?

instead of this

val myMap = Map("1" -> "2", "3"->"4") 
var s = ""
myMap foreach s += ...

i'd rather it be

var s = myMap something ...
like image 539
user747980 Avatar asked May 12 '11 22:05

user747980


1 Answers

I'd just map and mkString. For example:

val s = (
    Map("1" -> "2", "3"->"4") 
    map { case (key, value) => "Key: %s\nValue: %s" format (key, value) } 
    mkString ("", "\n", "\n")
)
like image 138
Daniel C. Sobral Avatar answered Oct 24 '22 03:10

Daniel C. Sobral