Scala String Interpolation
String interpolation lets you embed values and expressions directly inside string literals. Instead of joining strings with +, you place variables right inside the text. Scala provides three interpolation modes — s, f, and raw — each suited for different needs.
The Problem Without Interpolation
val name = "Priya"
val score = 95
// Old-style concatenation — cluttered and error-prone
println("Name: " + name + ", Score: " + score + "/100")
s Interpolation — Basic Embedding
Prefix the string with s and use $variable to embed values:
val name = "Priya"
val score = 95
println(s"Name: $name, Score: $score/100")
// Name: Priya, Score: 95/100
For expressions (not just simple variables), wrap them in curly braces ${...}:
val price = 250.0
val qty = 3
println(s"Total: ${price * qty}") // Total: 750.0
println(s"Doubled: ${score * 2}") // Doubled: 190
println(s"Name length: ${name.length}") // Name length: 5
println(s"Upper: ${name.toUpperCase}") // Upper: PRIYA
How s Interpolation Works
s"Hello, $name! You scored ${score + 5}."
│ │ │
│ └─ simple var └─ expression in braces
└─ prefix tells Scala: this is an s-interpolated string
Compiler transforms this to:
"Hello, " + name + "! You scored " + (score + 5) + "."
f Interpolation — Formatted Output
The f interpolator adds printf-style format specifiers for precise control over number formatting:
val pi = 3.141592653589793
val distance = 12345.6789
val percentage = 0.8756
println(f"Pi to 2 decimal places: $pi%.2f")
// Pi to 2 decimal places: 3.14
println(f"Distance: $distance%,.2f km")
// Distance: 12,345.68 km
println(f"Success rate: ${percentage * 100}%.1f%%")
// Success rate: 87.6%
val name = "Aarav"
println(f"$name%-10s | $pi%8.3f")
// Aarav | 3.142
Common Format Specifiers
Specifier Meaning Example Input Output
────────── ─────────────────────── ───────────── ───────────
%d Integer 42 42
%f Floating point 3.14159 3.141590
%.2f 2 decimal places 3.14159 3.14
%8.2f Width 8, 2 decimals 3.14159 3.14
%-8.2f Left-aligned width 8 3.14159 3.14
%s String "hello" hello
%-10s Left-aligned width 10 "hi" hi
%10s Right-aligned width 10 "hi" hi
%,d Integer with commas 1234567 1,234,567
%e Scientific notation 123456.789 1.234568e+05
%% Literal percent sign — %
f Interpolation for Aligned Tables
val items = List(("Apples", 5, 30.0), ("Bananas", 12, 15.5), ("Cherries", 3, 120.0))
println(f"${"Item"}%-12s ${"Qty"}%5s ${"Price"}%8s ${"Total"}%10s")
println("-" * 40)
for (name, qty, price) <- items do
println(f"$name%-12s $qty%5d $price%8.2f ${qty * price}%10.2f")
Output:
Item Qty Price Total
----------------------------------------
Apples 5 30.00 150.00
Bananas 12 15.50 186.00
Cherries 3 120.00 360.00
raw Interpolation — No Escape Processing
The raw interpolator embeds variables like s but does not process escape sequences. Backslashes are treated as literal characters:
val path = "users"
println(s"Path: C:\\Users\\$path") // Path: C:\Users\users
println(raw"Path: C:\Users\$path") // Path: C:\Users\users
println(s"Line1\nLine2") // two lines
println(raw"Line1\nLine2") // Line1\nLine2 (no newline!)
Use raw for regex patterns and Windows file paths where backslashes are common.
Multi-line s Interpolation
Combine triple quotes with s for multi-line interpolated strings:
val firstName = "Rohan"
val lastName = "Verma"
val age = 28
val city = "Pune"
val bio = s"""
Name: $firstName $lastName
Age: $age years
City: $city
Born: ${2024 - age}
""".strip
println(bio)
// Name: Rohan Verma
// Age: 28 years
// City: Pune
// Born: 1996
Interpolation with Case Classes
case class Product(name: String, price: Double, stock: Int)
val p = Product("Wireless Headphones", 2999.0, 47)
println(s"Product: ${p.name}")
println(f"Price: ₹${p.price}%,.0f")
println(s"In stock: ${p.stock} units")
println(s"Available: ${p.stock > 0}")
val receipt = s"""
=== Receipt ===
Item : ${p.name}
Price : ₹${p.price}
Qty : 1
Total : ₹${p.price}
""".strip
println(receipt)
Custom Interpolators
You can define your own interpolators by adding extension methods to StringContext. This is an advanced feature used in libraries like SQL query builders:
// Built-in example: sql interpolator pattern
// Libraries like Doobie use:
// sql"SELECT * FROM users WHERE id = $userId"
// The sql interpolator builds a safe parameterized query
Choosing the Right Interpolator
Situation Use
────────────────────────────── ─────
Embed variables in text s"..."
Format numbers (decimals/width) f"..."
Regex, Windows paths, raw text raw"..."
Multi-line with variables s"""..."""
Multi-line raw (no escapes) raw"""..."""
Common Mistakes
// WRONG: forgot s prefix
val n = 42
println("Value is $n") // prints literally: Value is $n
// CORRECT
println(s"Value is $n") // Value is 42
// WRONG: complex expression without braces
println(s"Double: $n * 2") // Double: 42 * 2 (only $n expanded)
// CORRECT
println(s"Double: ${n * 2}") // Double: 84
String interpolation is one of the features that makes Scala code clean and expressive. It removes the visual noise of string concatenation and makes the intent of formatted output immediately obvious.
