Scala - String Interpolation



You can create and format strings by inserting expressions directly into string literals using String interpolation. String interpolation can replace variables and expressions in a string with their actual values. We will discuss String interpolation in this post.

String Interpolation

String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal.

String Interpolation Basic Operations

There are three types (interpolators) of implementations in String Interpolation: s, f, and raw. Each of these has distinct purposes and unique features for string manipulation.

  • Strings need to start with either 's', 'f', or 'raw'.
  • Variables in the string should start with '$'.
  • Expressions should be enclosed in curly braces ({ }) and prefixed with '$'.

The 's' String Interpolator

The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator.

Example

The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement

val name = "James" println(s "Hello, $name") //output: Hello, James

String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’.

println(s "1 + 1 = ${1 + 1}") //output: 1 + 1 = 2

Example

Try the following example program of implementing 's' interpolator:

Open Compiler
object Demo { def main(args: Array[String]) { val name = "James" println(s"Hello, $name") println(s"1 + 1 = ${1 + 1}") } }

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

Hello, James
1 + 1 = 2

The 'f' Interpolator

The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc.

Example

Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90.

val height = 1.9d val name = "James" println(f"$name%s is $height%2.2f meters tall") //James is 1.90 meters tall

It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is no % character after variable reference. It will assume as %s (String).

The 'raw' Interpolator

The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string. The following code snippets in a table will differ the usage of ‘s’ and ‘raw’ interpolators. In outputs of ‘s’ usage ‘\n’ effects as new line and in output of ‘raw’ usage the ‘\n’ will not effect. It will print the complete string with escape letters.

s interpolator usage raw interpolator usage

Program

object Demo {
   def main(args: Array[String]) {
      println(s"Result = \n a \n b")
   }
}

Program

object Demo {
   def main(args: Array[String]) {
      println(raw"Result = \n a \n b")
   }
}

Output

Result =
a
b

Output

Result = \n a \n b

Advanced Usage of String Interpolation

You can also use String interpolation in more complex expressions and operations within the string literals.

1. Expressions within Interpolations

You can include any Scala expression within an interpolated string by enclosing it in curly braces.

For example:

val a = 5 val b = 10 println(s"The sum of $a and $b is ${a + b}.")

The output will be:

The sum of 5 and 10 is 15.

2. Multiline Strings

You can use interpolation for multiline strings which has format output spanning multiple lines.

For example:

val name = "Scala" val version = "2.13.6" println(s""" |Hello, $name! |You are using version $version. |""".stripMargin)

The output will be:

Hello, Scala!
You are using version 2.13.6.
Advertisements