Scala · Basics

String Interpolation

Interpolators build readable strings with values embedded directly.

Intermediate 5 min Lesson 7 of 25Examples use Scala 3 (3.3 LTS or newer) with sbt or scala-cli.
Before you start:Functions
0/25 in Scala
On this page · 5 min · Intermediate

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#

ScalaBuilding a receipt Illustrative
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)
Expected output
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#

  1. s inserts the name and an expression.
  2. f formats with thousands separators and 2 decimals.
  3. raw leaves backslashes untouched.
  4. 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#

Forgetting the s prefix

"Hello $name" prints the literal text $name.

Missing braces for expressions

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
Scala Illustrative
println(f"Pi is ${math.Pi}%.2f")

Mini quiz#

String Interpolation quizMultiple choice Question 1 of 1

Which interpolator formats numbers and is type-checked?

Score so far: 0/0

Want more? Practise all Scala MCQs · Scala interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.