← Back to Scala Course | Chapter 2: Variables & Types | Lesson 8 of 8

String Interpolation

In this page:

  1. String Interpolation

String Interpolation

The s"..." interpolator embeds expressions in a string with $name or ${expression}. The f"..." interpolator adds printf-style formatting, like f"$price%.2f" for two decimal places. The raw"..." interpolator disables escape sequence processing, so raw"\n" stays as the literal two characters backslash-n instead of becoming a newline.

Note: Use f-interpolation, like f"$price%.2f", whenever you need precise numeric formatting instead of the default toString.

Example: String Interpolation

markup
object Main extends App {
  val name = "Ruby"
  val price = 19.5

  println(s"Hello, $name!")
  println(f"Price: $price%.2f")
  println(raw"Raw newline stays literal: \n")
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.