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

String Interpolation

String interpolation lets you drop values right into a sentence, like filling blanks in a story as you write it. You put a dollar sign in front of the name and Scala fills it in.

In this page:

  1. String Interpolation
Syntax
scala
val name = "value"
println(s"text $name more text")
println(s"sum: ${expression}")

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")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the s before the quotes, as in "Hello, $name!", which prints $name literally.
  2. Writing s"$price%.2f" and expecting formatting, when only f"$price%.2f" applies the format.
  3. Using $obj.field and getting the wrong result, when an expression needs braces such as ${obj.field}.
Chapter Summary
  • val declares immutable values and var declares mutable ones.
  • Scala has types such as Int, Double, Boolean, Char, and String, and the compiler can often infer them.
  • Unit and string interpolation round out the basics.
🔒

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.