Scala - modifying a string in a functional way

I am just starting out Scala and therefore get the head out of doing things in a more functional style.

Just wondering if there is a more functional way to achieve something like the following:

def expand(exp: String): String = { var result = exp for ((k,v) <- libMap) {result = result.replace(k, "(%s)".format(v))} result } 

Or in general terms, given a string and some iterable collection, browse through the collection and gradually change the input string for each item.

Greetings

+5
source share
1 answer

Usually a pattern

 var result = init for (foo <- bar) { result = f(result, foo)} result 

can be expressed functionally as

 bar.foldLeft(init)(f) 

So, for your case, this is becomas:

 libMap.foldLeft(exp){ case(result, (k,v)) => result.replace(k, "(%s)".format(v))} 
+8
source

All Articles