Scala – String Interpolation

In the previous post, we have learnt about string literal and its basic functions in scala. In this post, we will see a concept called String interpolation introduced in scala version 2.10 that helps in processing the string in a better way similar to other languages like Perl, PHP and Ruby.

What is string Interpolation?

As we know that string is a sequence of characters and sometimes we can have a string as combination of characters, variables or expressions. Scala provides a way to replace this variables or expressions with expected values and this concept is called String Interpolation.

Types of String Interpolation:

String interpolation are having following categories.

  • s String Interpolator
  • f String Interpolator
  • raw String Interpolator

We will understand them one by one with examples.There are some rules that we need to follow to work with string Interpolation.

Rules to follow:

  • String must be started with s/f/raw.
  • Each variable or expression will have a ‘$’ as prefix.
  • Expression must be enclosed within curly braces {}.

Let’s start with s string interpolation and understand it with an example. The most common use of string interpolation can be seen as string concatenation. If you will look at the below example where we are concatenating ‘hello‘ with name variable.

s String Interpolator:

This interpolator can be used to access variable, object ,function calls etc.

Example1: Access variable in String literal

We are defining variables as firstname and lastname and using s interpolator to use it in string starting with s.

Example2: Access object fields in string literals

Example3: Access function call in string literal

Example4: Handle expression in string literal

f String Interpolator:

This interpolator helps in number formatting. To use it , we place the instructions after the expression , starting with percent sign (%). Suppose , we have a weight given as 100.0 and we wan to add more decimal to it or completely remove it. How can we do that? We will use f string interpolator to achieve this.

raw String Interpolator:

When we don’t want to evaluate escape character, we should use raw string interpolator. If we have \n in the string literal and it starts with raw, then it will accept \n as it is. That means it does not evaluate \n as new line character.

Scala - String
Scala - Add your own method to String class
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *