Scala - String Concatenation Operator



Scala supports string concatenation using the + operator; it concatenates two strings and returns the concatenated string as a result.

Syntax

The Syntax of the string concatenation operator −

val result = str1 + str2

The + operator in Scala concatenates two strings. For example: str1 + str2 will concatenate str1 and str2.

Example of Scala String Concatenation Operator

Try the following example program to understand string concatenation operator available in Scala programming language −

object Demo {
   def main(args: Array[String]) = {
      val str1 = "Hello"
      val str2 = "World"
      val result = str1 + str2
      
      println(result) // Output: HelloWorld
   }
}

The + operator in Scala is used between two strings (str1 and str2 in this case). It concatenates them to form a single string ("HelloWorld"). This can concatenate strings of any length or content. The result of concatenation (result) is then printed to the console using println.

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

HelloWorld
Advertisements