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();
if (b) {
return s.toString();

Answer Source

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 "" ) +
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download