🎓 A1Learner
🔍
0 of 50 lessons completed

Scala String Interpolation

String interpolation is a way to place values directly inside a string of text. An s before the quotes inserts values with $, and an f before the quotes also controls how numbers are formatted.

The $ sign inserts a value by name

The s before the quotes turns on insertion. The name after $ is replaced by its stored value.

@main def main(): Unit =
  val name = "Ana"
  println(s"Hello, $name!")

Braces insert a calculated result

The calculation inside ${ } is worked out first. Its result takes the place of the braces in the text.

@main def main(): Unit =
  println(s"3 + 4 = ${3 + 4}")
  println(s"Total: ${4 * 3}")

The f string formats decimal numbers

The %.2f code after each value forces two digits after the decimal point. Whole amounts gain .00 and half amounts show .50.

@main def main(): Unit =
  val price = 9.5
  val cost = 3.0
  println(f"Price: $price%.2f")
  println(f"Cost: $cost%.2f")

Example

@main def main(): Unit =
  val item = "Book"
  val price = 12.5
  val count = 2
  val total = price * count
  println(s"Item: $item")
  println(s"Count: $count")
  println(f"Total: $total%.2f")

Key points

  • s string: a string starting with s lets $ followed by a name insert that value.
  • Braces: ${ } inserts the result of a calculation inside the string.
  • f string: a string starting with f lets a format code shape a number.
  • Format code: %.2f after a value prints a decimal number with two digits after the point.
  • Result: interpolation builds one finished string that can be printed like any other string.

In this example, the s strings insert the item name and the count into the text. The total is worked out as 12.5 times 2, and the f string prints it as 25.00 with two decimal digits.

Note

in Scala the letter before the opening quote decides the power of the string, s for inserting and f for formatting.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does println(f"$price%.2f") print when price is 9.5?