String Concatenation
String concatenation glues pieces of text together with a plus sign, like clicking train cars into one long train. Scala can even join a number to text for you.
In this page:
Syntax
val result = string1 + string2
val message = "text " + value
String Concatenation
The + operator joins strings together, and Scala automatically converts non-string operands to their string form when one side is already a String.
While + works fine for simple cases, string interpolation is generally preferred for building strings with multiple embedded values, since it's more readable. Both approaches ultimately produce a new immutable String.
Note:
For more than a couple of concatenated pieces, string interpolation (
s"...") reads more clearly than chained + operators.Example: String Concatenation
object Main extends App {
val first = "Hello"
val second = "Scala"
val combined = first + ", " + second + "!"
println(combined)
println("Count: " + 42)
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Concatenating a number first, as in
1 + 2 + "a", which gives3a, not12a. - Building a long string with
+in a loop, when aStringBuilderis more efficient. - Using
+with anullstring, so the textnullappears in the result.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: