Jiří Vypědřík Jiří Vypědřík - 1 month ago 13
Scala Question

The most idiomatic way to perform conditional concatenation of strings in Scala

I'm curious what would be the best way to build a String value via sequential appending of text chunks, if some of chunks dynamically depend on external conditions. The solution should be idiomatic for Scala without much speed and memory penalties.

For instance, how one could re-write the following Java method in Scala?

public String test(boolean b) {
StringBuilder s = new StringBuilder();
s.append("a").append(1);
if (b) {
s.append("b").append(2);
}
s.append("c").append(3);
return s.toString();
}

Answer

Since Scala is both functional and imperative, the term idiomatic depends on which paradigm you prefer to follow. You've solved the problem following the imperative paradigm. Here's one of the ways you could do it functionally:

def test( b : Boolean ) =
  "a1" + 
  ( if( b ) "b2" else "" ) +
  "c3"
Comments