The most idiomatic way to do conditional string concatenation in Scala

I'm curious what would be the best way to build a String value by adding text fragments in succession if some of the pieces are dynamically dependent on external conditions. The solution should be idiomatic for Scala without any particular speed and memory limitations.

For example, how can I rewrite 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(); } 
+6
source share
5 answers

Since Scala is functional and imperative, the idiomatic term depends on the paradigm that you prefer to follow. You solved the problem by following the imperative paradigm. Here is one way to do this functionally:

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

How to make own components of string functions own? They must make a decision, which is a sufficient responsibility for the function in my book.

 def test(flag: Boolean) = { def a = "a1" def b = if (flag) "b2" else "" def c = "c3" a + b + c } 

An additional advantage of this is that it clearly breaks the various components of the final line, giving a general overview of how they fit together at a high level, without any restrictions, in the end.

+3
source

As @ om-nom-nom said, your idiomatic code is already enough

 def test(b: Boolean): String = { val sb = new StringBuilder sb.append("a").append(1) if (b) sb.append("b").append(2) sb.append("c").append(3) sb.toString } 

I can offer an alternative version, but it is not necessarily more effective or "scala -ish"

 def test2(b: Boolean): String = "%s%d%s%s%s%d".format( "a", 1, if (b) "b" else "", if (b) 2 else "", "c", 3) 
+1
source

Nowadays, idiomatic means string interpolation.

scala s"a1${if(b) "b2"}c3"

You can even nest string interpolation:

scala s"a1${if(b) s"$someMethod"}"

+1
source

In scala, a string can be thought of as a sequence of characters. Thus, an idiomatic functional way to solve your problem would be with map :

 "abc".map( c => c match { case 'a' => "a1" case 'b' => if(b) "b2" else "" case 'c' => "c3" case _ => }).mkString("") 
0
source

Source: https://habr.com/ru/post/945254/


All Articles