Scala String Interpolation

Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is called string interpolation. String interpolation allows users to embed variable references directly in processed string literals. Scala provides three string interpolation methods: s, f and raw.


Scala Program Example: Without using s Method

This is simple example which does not use s method in string.

Output:

value of pi = 3.14

Scala String Interpolation Example

This program use string interpolation in print function. You can see the advantage of interpolation. Here, we did not use + operator to concatenate string objects.

Output:

value of pi = 3.14

Scala String Interpolation Example By using s Method

The s method of string interpolation allows us to pass variable in string object. You don't need to use + operator to format your output string. In the following example, a string variable is passed to string in the print function. This variable is evaluated by compiler and variable is replaced by value.

Output:

This is Scala string example

Scala String Interpolation Example By using f Method

The f method is used to format your string output. It is like printf function of c language which is used to produce formatted output. You can pass your variables of any type in the print function.

Output:

This is Scala string example, scala version is 2.12

Scala String Interpolation Example By using raw Method

The raw method of string interpolation is used to produce raw string. It does not interpret special char present in the string. Let's see an example.

Output:

Scala	string 
example
Scala \nstring \nexample




Contact US

Email:[email protected]

Scala String Interpolation
10/30