'S' string interpolator
object Demo {
def main(args: Array[String]) {
val name = "James"
println(s"Hello, $name")
println(s"1 + 1 = ${1 + 1}")
}
}
def main(args: Array[String]) {
val name = "James"
println(s"Hello, $name")
println(s"1 + 1 = ${1 + 1}")
}
}
Output:
Hello, James
1 + 1 = 2
=========================================================================
The ‘ f ’ Interpolator
- The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language.
- While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc.
Program
object Demo {
def main(args: Array[String]) {
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall")
}
}
Output:
James is 1.90 meters tall
=========================================================================
raw interpolator
The ‘raw’ interpolator is similar to ‘s’ interpolator except that it performs no escaping of literals within a string.
Program
object Demo {
def main(args: Array[String]) {
//without raw Interpolator
println(s"Result = \n a \n b")
//with raw Interpolator
println(raw"Result = \n a \n b")
}
}
Output:
Result =
a
b
Result = \n a \n b
=========================================================================
Interpolator Basic Example:
Program
object HelloWorld {
def main(args : Array[String]){
val name="mark"
val age=18
// 1st Method With Concatenation
println(name + " is " + age +" years old ")
//2nd Method
println(s"$name is $age years old")
//3rd Method
println(f"$name%s is $age%d years old")
//4th Method
println(f"$name%s is $age%f years old")
//5th Method: raw interpolation
println(s"hello, \n world")
println(raw"hello, \n world")
}
}
Output:
mark is 18 years old
mark is 18 years old
mark is 18 years old
mark is 18.000000 years old
hello,
world
hello, \n world