Answer the question
In order to leave comments, you need to log in
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
You can use StringBuilder, but you will only benefit if there are a lot of string operations.
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.
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
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
^
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 questionAsk a Question
731 491 924 answers to any question