← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 5 of 7

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:

  1. String Concatenation
Syntax
scala
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

markup
object Main extends App {
  val first = "Hello"
  val second = "Scala"
  val combined = first + ", " + second + "!"

  println(combined)
  println("Count: " + 42)
}
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
  1. Concatenating a number first, as in 1 + 2 + "a", which gives 3a, not 12a.
  2. Building a long string with + in a loop, when a StringBuilder is more efficient.
  3. Using + with a null string, so the text null appears in the result.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.