VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-string-interpolation/

⇱ Scala | String Interpolation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala | String Interpolation

Last Updated : 11 Jul, 2025
String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules:
  1. String must be defined with starting character as s / f /raw.
  2. Variables in the String must have '$' as prefix.
  3. Expressions must be enclosed within curly braces ({, }) and '$' is added as prefix.
Syntax:
// x and y are defined
val str = s"Sum of $x and $y is ${x+y}"
  1. s Interpolator: Within the String, we can access variables, object fields, functions calls, etc. Example 1: variables and expressions: Output:
    str1: Sum of $x and $y is ${x+y}
    str2: Sum of 20 and 10 is 30
    Example 2: function call Output:
    str1: Sum of $x and $y is ${add(x, y)}
    str2: Sum of 20 and 10 is 30
  2. f Interpolator: This interpolation helps in formatting numbers easily. To understand how format specifiers work refer Format Specifiers. Example 1: printing upto 2 decimal place: Output:
    str1: Value of x is $x%.2f
    str2: Value of x is 20.60
    Example 2: setting width in integers: Output:
    Value of x is $x%04d
    Value of x is 0011
    If we try to pass a Double value while formatting is done using %d specifier, compiler outputs an error. In case of %f specifier, passing Int is acceptable.
  3. raw Interpolator: String Literal should start with β€˜raw’. This interpolator treats escape sequences same as any other character in a String. Example :printing escape sequence: Output:
    str1: Hello
    World
    str2: Hello\nWorld
Comment
Article Tags:
Article Tags:

Explore