A
A
Alexander2016-01-19 18:21:53
Scala
Alexander, 2016-01-19 18:21:53

Scala. How to concatenate strings correctly?

Hello.
I wrote a test task in Scala (for the first time I saw this PL), and today an answer came from the employer on my task.
Asserts that it is wrong to use + for string concatenation in Scala. I am aware that String has a concat method that does the same, but in my case it is more convenient (and more familiar) to use +
How is it correct to add strings, and what is the difference between + and concat ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem Kileev, 2016-01-19
@akileev

You can use StringBuilder, but you will only benefit if there are a lot of string operations.

A
Artem, 2016-01-19
@mrRontgen

Maybe you were expected to use a functional paradigm/pattern (some kind of fold(...) ) at this point? And you added strings by imperative...
All ways of concatenating strings in a test task will lead to the same result, but they will show different ways of thinking and approach to solving the problem.

A
Alexander, 2016-02-05
@a1go1ov

Really really lacks context. Perhaps there were some details in the task that indicated the correct way, from the point of view of the task . Since Scala strings are java strings , the same rules apply to them.
If you use `+` then, for example, this expression will not cause an error:

scala> "one" + null + 42
res0: String = onenull42

that is, when a string is concatenated with values ​​of other types, these values ​​are converted to a string behind the scenes (the toString() method is called).
On the other hand , concat only accepts strings:
scala> "" concat null
java.lang.NullPointerException
  at java.lang.String.concat(String.java:2027)
  ... 33 elided

scala> "" concat 42
<console>:11: error: type mismatch;
 found   : Int(42)
 required: String
       "" concat 42
                 ^

From a performance point of view, strings in java (and, as a result, in Scala) are immutable and the + operator creates a new string each time when concatenating a large number of strings, which, of course, is not very efficient when concatenating a large number of strings and the concat method will work faster in such a situation. On the other hand, the compiler is able to optimize simple use cases of the + operator and convert them using StringBuilder (which is mutable) and it in turn is more performant than concat.
In general, if the job had a hint of the need to concatenate a large number of strings and performance sensitivity, then it was necessary to use StringBuilder. If it was necessary to show a more scala way, then perhaps the best option would be to use interpolation :
scala> val (one, two, three) = (1, "two", null)
one: Int = 1
two: String = two
three: Null = null

scala> s"$one $two $three"
res11: String = 1 two null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question