Scala String Interpolation

String interpolation is a feature of Scala and it enables us to embed variable references directly in processed string literals.

We have three kinds of Scala String interpolators. Let’s see them one by one.

s String interpolator
f String interpolator
raw String interpolator

s String interpolator:

When we prepend ‘s’ to any string, we can directly use variable in it with the use of $ character. But that variable should be in scope.


  val name = "John"
  println(s"My Name is $name")  // My Name is John

f string  interpolator
When we prepend ‘f’ to a processed string literal which allows  the creation of formatted strings, Its similar to “printf” in Java.


val height = 1.9d
val name = "John"
println(f"$name%s is $height%.2f meters tall")  // John is 1.90 meters tall

raw interpolator
It’s similar to ‘s’ interpolator except that it performs no escaping of literals within the string.

Refer the below example,


val name="John"
println(s"My name is \n$name")  //My name is
                                //John  

Here the s interpolator, replaced the character \n with a return character.  The “raw” interpolator will not do that.


val name="John"
println(raw"My name is \n$name") //My name is \n John

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s