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();
}
If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.
Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. we can also use '+' operator to concatenate two strings. Syntax: str1.
We can use the % operator for string formatting, it can also be used for string concatenation.
Concatenating strings using + is not efficient. The time complexity of string concatenation using + is O(n²)
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"
These days, idiomatic means string interpolation.
s"a1${if(b) "b2" else ""}c3"
You can even nest the string interpolation:
s"a1${if(b) s"$someMethod" else ""}"
What about making the different components of the string functions in their own right? They have to make a decision, which is responsibility enough for a function in my book.
def test(flag: Boolean) = {
def a = "a1"
def b = if (flag) "b2" else ""
def c = "c3"
a + b + c
}
The added advantage of this is it clearly breaks apart the different components of the final string, while giving an overview of how they fit together at a high level, unencumbered by anything else, at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With