String Interpolation
Interpolators build readable strings with values embedded directly.
On this page · 5 min · Intermediate
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 30, 2026
Related tutorials
In simple words#
An interpolated string is a form letter with blanks: “Dear $name, your bill is $amount.” Scala fills in the blanks for you.
- s"…"
- Insert $name or ${expression}.
- f"…"
- Formatted: $price%.2f.
- raw"…"
- No escape processing.
Learning objectives#
- Use the s interpolator
- Format numbers with f
- Write multi-line strings
- Use raw strings
Explanation#
s"Hello $name" inserts a variable; s"Total ${a + b}" inserts any expression.
f"$price%.2f" formats like printf and is type-checked at compile time.
raw"C:\new\folder" keeps backslashes as-is.
Triple quotes """…""" create multi-line strings; stripMargin removes leading spaces up to |.
Code example: Building a receipt#
val customer = "Asha"
val items = List(("Laptop", 55000.0), ("Mouse", 1399.5))
val total = items.map(_._2).sum
println(s"Hello $customer, you bought ${items.size} items")
println(f"Total: ₹$total%,.2f")
println(raw"Saved to C:
eports
ew")
val receipt =
s"""|RECEIPT
|Customer: $customer
|${items.map((n, p) => f"$n%-8s ₹$p%10.2f").mkString("
")}
|""".stripMargin
print(receipt)
Hello Asha, you bought 2 items Total: ₹56,399.50 Saved to C: eports ew RECEIPT Customer: Asha Laptop ₹ 55000.00 Mouse ₹ 1399.50
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- s inserts the name and an expression.
- f formats with thousands separators and 2 decimals.
- raw leaves backslashes untouched.
- stripMargin tidies the multi-line receipt.
Real-world use case#
Logging, emails and reports are built with interpolated strings instead of messy concatenation.
Common mistakes#
"Hello $name" prints the literal text $name.
s"$a.b" inserts only a. Use s"${a.b}".
Best practices#
- s for simple text
- f for numbers
- stripMargin for multi-line
- Avoid + concatenation
Remember this#
s = insert, f = format, raw = no escapes.
${…} for expressions.
"""…""".stripMargin for blocks.
Practice exercise#
Your task: Print "Pi is 3.14" using f-interpolation with math.Pi.
Show solution
println(f"Pi is ${math.Pi}%.2f")
Mini quiz#
Which interpolator formats numbers and is type-checked?
Want more? Practise all Scala MCQs · Scala interview questions
My notes#
Saved in this browser.