Skip to Content
Course content

8: String Interpolation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a PR from a junior dev who was building a custom logging system for a financial pipeline. He was using the old-school Java approach of concatenating strings with the + operator. He had this one monstrous line—about six different variables and several hard-coded strings—all smashed together to create a transaction summary. He'd missed a single space before a WHERE clause in a dynamically built query, and the app was throwing a syntax error that took him two hours to find because, visually, the code looked like there was a space there.

That's the danger of "string plumbing." When you spend more time managing quotes and plus signs than thinking about the actual message, you're asking for bugs. In Scala, we solve this with string interpolation, which lets you embed variables and expressions directly into a string literal.

Embedding Variables with the s-interpolator

The most common tool you'll use is the s interpolator. By prefixing your string with an s, you tell Scala that anything starting with a $ sign is a variable that needs to be evaluated. It's much cleaner than jumping in and out of quotes every few words.

val user = "Alice"
val balance = 450.25
val status = "Active"

// The old, painful way
val legacy = "User: " + user + " has a balance of " + balance + " and status is " + status

// The Scala way
val modern = s"User: $user has a balance of $balance and status is $status"

Now, sometimes you need to do more than just drop in a variable. If you want to call a method or perform a calculation inside the string, you wrap the expression in curly braces: ${}. I usually suggest using the braces even for simple variables if the surrounding text is confusing, just to make it crystal clear where the variable name ends and the string begins.

val item = "Laptop"
val price = 1200
val taxRate = 0.15

val receipt = s"The total for the ${item.toUpperCase} is ${price * (1 + taxRate)}"

Precision Control with the f-interpolator

While the s interpolator is great for general use, it's terrible for numbers. If you've ever printed a Double and ended up with 12.300000000000001, you know exactly what I mean. For these cases, I always reach for the f interpolator.

The f interpolator uses printf-style formatting. It allows you to specify exactly how many decimal places you want or how much padding a string should have. The trade-off is that it's more rigid—it requires a type-safe format specifier for every single variable you interpolate.

val pi = 3.1415926535
val amount = 1234.5678

// %.2f means "floating point with 2 decimal places"
val formatted = f"The value of pi is roughly $pi%.2f and the total is $$$amount%.2f"
// Output: The value of pi is roughly 3.14 and the total is $1234.57

Notice how I used $$ in the example above? Because $ is a special character in interpolators, you have to double it up if you want a literal dollar sign to appear in your output. I've lost a fair amount of time to "missing dollar sign" bugs in my early Scala days.

Handling Raw Text and Regex with raw

Finally, there's the raw interpolator. Normally, Scala processes escape characters like \n (newline) or \t (tab). But when you're writing regular expressions or file paths for Windows, those backslashes become a nightmare because you have to double-escape everything.

The raw interpolator tells Scala to leave the string exactly as it is written, while still allowing you to embed variables. It's a lifesaver for configuration strings or any text where backslashes are common.

val folder = "Users"
val path = raw"C:\$folder\Documents\Notes.txt"
// Output: C:\Users\Documents\Notes.txt (without needing \\)



📋 Practical Task

Build a Transactional Audit Log Formatter

You are building a logging utility for a banking application. Your task is to create a function that takes a transaction's details and returns a perfectly formatted audit string.

Requirements:

  • Create a function formatTransaction(userId: String, amount: Double, currency: String, timestamp: String).
  • Use the f interpolator to ensure the amount is displayed with exactly two decimal places.
  • Use the s interpolator (or integrate it) to ensure the userId is converted to uppercase.
  • The final string must follow this exact pattern: [AUDIT] User: USERID | Amount: CURRENCY 0.00 | Date: TIMESTAMP.

Example Input:
formatTransaction("jdoe88", 1250.5, "USD", "2023-10-27 10:00")

Expected Output:
[AUDIT] User: JDOE88 | Amount: USD 1250.50 | Date: 2023-10-27 10:00

Rating
0 0

There are no comments for now.

to be the first to leave a comment.