...

/

String Interpolation with 'f'

String Interpolation with 'f'

In the following lesson, you will be introduced to the 'f' string interpolator.

Remember when we discussed the printf method when learning how to print? printf is actually a Java method which is recognized by Scala. However, it is unconventional to use printf in Scala as it has its own, arguably better, printf.

The f String Interpolator

The f string interpolator is Scala’s printf. For string interpolation with f, we prepend an f to any string literal. This allows us to create formatted strings. When using the f interpolator, all references to variables and expressions should be followed by a printf-style format string, like %f.

Let’s look at an example:

Scala
val pi = 3.14159F
println(f"the value of pi is $pi%.2f")

In the code above, f"the value of pi is $pi%.2f" is a processed string literal. The f prepended before the string is letting the compiler know that the string should be processed using the f interpolator. pi is our variable identifier and %.2f is our format specifier and is formatting the string by telling the compiler to only print the floating-point number pi up to two decimal places.

Try replacing the 2 ...