Scala Strings
Data Types introduced string literals and basic
s"..." interpolation. This page goes further: the other interpolators, the common StringOps methods you will use daily, mutable StringBuilder for building text in a loop, and regular expressions.
The Three Interpolators
Scala ships three string interpolators. All three start with a prefix letter right before the opening quote.
| Prefix | Name | Purpose |
|---|---|---|
s"..." | Standard | Substitutes $identifier and ${expression}. |
f"..." | Formatted | Same substitution, plus printf-style format specifiers like %d, %.2f. |
raw"..." | Raw | Substitutes like s"..." but does not process escape sequences such as \n. |
Example:
val name = "Ana"
val price = 19.5
println(s"Hello, $name!") // Hello, Ana!
println(f"Total: $$${price}%.2f") // Total: $19.50
println(raw"Line one\nLine two") // Line one\nLine two (no real newline)
Common StringOps Methods
Every String in Scala is a Java String enriched with dozens of extra methods via StringOps. You get the safety of an immutable value with a collection-like API on top.
| Method | What it does |
|---|---|
.trim | Removes leading and trailing whitespace. |
.split(sep) | Splits into an Array[String] on a separator (regex-aware). |
.replace(a, b) | Replaces every literal occurrence of a with b. |
.contains(sub) | True if sub appears anywhere in the string. |
.toUpperCase / .toLowerCase | Case conversion. |
.reverse | Reverses the characters. |
.padTo(n, ch) | Pads on the right with ch until length n. |
.stripMargin | Strips leading whitespace and a leading | from each line of a multiline string. |
.toIntOption | Parses to Option[Int] instead of throwing — see Error Handling. |
Example:
val messy = " Scala, Kotlin, Java "
val parts = messy.trim.split(",").map(_.trim)
println(parts.mkString(" | ")) // Scala | Kotlin | Java
println("42".toIntOption) // Some(42)
println("nope".toIntOption) // None
StringBuilder
A String is immutable, so concatenating one in a loop rebuilds a new string every iteration. For heavy text building, use the mutable StringBuilder and call .toString once at the end.
Example:
val sb = new StringBuilder()
for (i <- 1 to 5) {
sb.append(i)
if (i < 5) sb.append(", ")
}
println(sb.toString) // 1, 2, 3, 4, 5
Regular Expressions
A Regex is created from any string with .r, or from the dedicated r"..." interpolator. Regex objects support pattern matching directly, which reads naturally in a match expression.
Example:
val datePattern = raw"(\d{4})-(\d{2})-(\d{2})".r
"2026-09-29" match {
case datePattern(year, month, day) =>
println(s"Year=$year Month=$month Day=$day")
case _ =>
println("Not a date")
}
// findAllIn returns every match as an iterator
val words = raw"\w+".r.findAllIn("Scala is fun").toList
println(words) // List(Scala, is, fun)