In Previous chapter we learned about SCALA LAZY EVALUATION and today lets check out SCALA STRING INTERPOLATION.
String Interpolation is a process of creating String from Data. Without further delay let me directly explain what it is.
1.There are 3 string interpolation method s , f & raw interpolator.
2.The variable should start with $ as prefix.
3.If any Expression is created then it needs to be enclosed inside {} braces.
Table of Contents
String – s Interpolator
Using this literal you can directly append variable to string. Lets check couple of examples with this.
scala> var name = "Paul" name: String = Paul scala> print(s"His name is $name" ) His name is Paul
In the above example the variable ‘name’ is replaced with Paul. The rule is we need to add interpolator s before the string and $ before the variable. When we print the same without providing the interpolator s, it assumes that the entire thing is a string and prints it as is.
scala> print("His name is $name" ) His name is $name
Also you can write expressions like below.
scala> var x = 5 x: Int = 5 scala> var y = 6 y: Int = 6 scala> println(s"The two numbers are $x and $y and when multiplied it gives value ${x * y}") The two numbers are 5 and 6 and when multiplied it gives value 30
String – F Interpolator
f interpolator allows user to create a formatted number. It does show by using f before the string and % after the variable . Lets understand this with an example. Print the mark of a student as floating point number.
scala> var marks =89 marks: Int = 89 scala> var studentname = "Paul" studentname: String = Paul scala> print(f"$studentname has got $marks in maths") Paul has got 89 in maths
You can see that the value 89 got printed but we wanted it to be of decimal type 89.0. To achieve this we need to use %f
scala> print(f"$studentname has got $marks%1.1f in maths") Paul has got 89.0 in maths
You can get a complete list of format specifiers to use with % here.
String – raw interpolator
Using raw interpolator you can use the escape literals as is. A funny way of explaining it is , the escape characters cannot escape now 🙂 . It does so by using raw before the string
scala> print("hi my name is\nmartin") hi my name is martin
In the above example you see that i used escape character \n so that i can display martin in next line. But what if i didn’t intend to do this and i wanted the data to be printed as is i.e with \n. Here we use raw interpolator
scala> print(raw"hi my name is\nmartin") hi my name is\nmartin
In the next chapter we will learn about SCALA PATTERN MATCHING