Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();
}
like image 848
Jiří Vypědřík Avatar asked May 17 '13 10:05

Jiří Vypědřík


People also ask

What is the most efficient way to concatenate many strings together?

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.

Which operator is used for concatenating strings in Scala?

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.

Which of the following can be used to perform string concatenation?

We can use the % operator for string formatting, it can also be used for string concatenation.

What is the time complexity of string concatenation?

Concatenating strings using + is not efficient. The time complexity of string concatenation using + is O(n²)


3 Answers

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"
like image 102
Nikita Volkov Avatar answered Jun 03 '23 16:06

Nikita Volkov


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 ""}"
like image 32
Scott Carey Avatar answered Jun 03 '23 17:06

Scott Carey


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.

like image 31
Russell Avatar answered Jun 03 '23 16:06

Russell