Scala

18 / 51
   

Scala - String Formatting and Interpolation

Formatting:
Strings can be formatted using printf() method to get output in required formats.

object Demo {
   def main(args: Array[String]) {
      var floatVar = 10.123
      var intVar = 5000
      var stringVar = "Hello There"

      var fs = printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the string" + "is %s", floatVar, intVar, stringVar);

      println(fs)
   }
}

Interpolation:
This mechanism evaluates the string value in runtime.
Strings can be interpolated or expanded using various ways.

  • The s interpolator

It allows the use of variable directly in processing a string, when you prepend ‘s’ to it.

val name = "John"
println(s "Hello $name") //output: Hello John

String interpolation can also process arbitrary expressions.

println(s "2 + 3 = ${2 + 3}") //output: 2 + 3 = 5
  • The f interpolator

It allows creating 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.

val height = 1.7d
val name = "John"
println(f"$name%s is $height%2.2f meters tall") //John is 1.70 meters tall
  • The raw interpolator

It is similar to s interpolator except that it performs no escaping of literals within a string.
Output with s option:

println(s"Result = \n a \n b")

Result = 
 a 
 b

Outout with raw option:

println(raw"Result = \n a \n b")

Result = \n a \n b