String Interpolation in Scala

Strings in scala support a feature called interpolation which provides a way to seamlessly use variables inside a string.

There are three basic interpolators:

  • s
  • f
  • raw

They function similar to JavaScript tags.

The s Interpolator

It is a very simple interpolator that just places the variables inside the string.

val firstName = "Roger";val middleName = "D.";val lastName = "Gol";val fullName = s"I am $lastName $middleName $firstName!";println(fullName);// I am Gol D. Roger!

But what if we need to use methods inside the string?

val firstName = "Roger";val middleName = "d."; // We need to capitalize thisval lastName = "Gol";val fullName = s"I am $lastName $middleName.toUpperCase $firstName!";println(fullName);// I am Gol d..toUpperCase Roger!

Definitely not what we wanted. In this case, we can use curly braces to group the entire value.

val fullName = s"I am $lastName ${middleName.toUpperCase} $firstName!";println(fullName);// I am Gol D. Roger!


The raw Interpolator

The raw interpolator is almost the same as the s interpolator, except that it escapes all special characters like \n.

val name = "Kaido";val msg1 = sname";println(msg1) /*  Hello,  Kaido*/val msg2 = raw"Hello,\n$name";println(msg2) /*  Hello,\nKaido*/

The f Interpolator

The f interpolator allows the use of format strings (like the ones used in C).

Each variable name should be immediately followed by a format string.

val pi = 3.14;println(f"Pi is $pi%1.0f");  // Pi is 3println(f"Pi is $pi%1.2f");  // Pi is 3.14println(f"Pi is $pi%1.9f");  // Pi is 3.140000000

The variables must match the data type. The compiler will otherwise throw an error.

println(f"Pi is $pi%d");  /*    error: type mismatch;    found   : Double    required: Int*/