Scala Strings & Interpolation
Scala's String is the same class as Java's java.lang.String, so all of Java's string methods are available. On top of that Scala adds string interpolation, multi-line strings and many collection-style methods.
Creating strings
@main def run(): Unit =
val first = "Ada"
val last = "Lovelace"
val full = first + " " + last
println(full)
println(full.length)
println(full.toUpperCase)
println(full(0)) // character at index 0
println(full.charAt(4))Ada Lovelace
12
ADA LOVELACE
A
L
Strings are immutable: methods such as toUpperCase return a new string and leave the original untouched.
The three interpolators
Put a letter in front of a string literal to turn it into an interpolated string.
| Interpolator | What it does | Example |
|---|---|---|
s"…" |
inserts values with $name or ${expression} |
s"Hi $name" |
f"…" |
like s, plus printf-style formats such as %.2f |
f"$price%.2f" |
raw"…" |
like s, but does not process escapes like \n |
raw"C:\new" |
@main def run(): Unit =
val item = "coffee"
val qty = 3
val price = 2.4
println(s"$qty x $item")
println(s"Total: ${qty * price}")
println(f"Total: ${qty * price}%.2f EUR")
println(f"[$item%10s] [$item%-10s] [$qty%04d]")
println(raw"Path: C:\new\table")
println(s"Escaped: a\tb")3 x coffee
Total: 7.199999999999999
Total: 7.20 EUR
[ coffee] [coffee ] [0003]
Path: C:\new\table
Escaped: a b
Tip: Use
${...}with braces whenever you insert anything more than a plain name — a method call, a calculation or a field such as${user.name}.
Multi-line strings
Triple quotes create a string that can span several lines and contain " freely. stripMargin removes everything up to and including a leading | on each line, so you can indent the text with your code.
@main def run(): Unit =
val name = "Kai"
val letter =
s"""Dear $name,
|Your order "B-17" has shipped.
| - The Shop""".stripMargin
println(letter)Dear Kai,
Your order "B-17" has shipped.
- The Shop
Useful string methods
@main def run(): Unit =
val text = " Scala is scalable "
val t = text.trim
println(s"[$t]")
println(t.contains("scal"))
println(t.startsWith("Scala"))
println(t.indexOf("is"))
println(t.replace("scalable", "fun"))
println(t.split(" ").toList)
println(t.substring(0, 5))
println(t.take(5) + "|" + t.drop(9))
println(t.reverse)
println("ab" * 3)
println("Mississippi".count(_ == 's'))
println("hello world".capitalize)[Scala is scalable]
true
true
6
Scala is fun
List(Scala, is, scalable)
Scala
Scala|scalable
elbalacs si alacS
ababab
4
Hello world
| Method | Purpose |
|---|---|
trim, strip |
remove surrounding whitespace |
toUpperCase, toLowerCase, capitalize |
change case |
contains, startsWith, endsWith |
test for a substring |
indexOf, lastIndexOf |
find a position (−1 if missing) |
split(sep) |
break into an Array[String] |
take(n), drop(n), substring(a, b) |
slice |
replace(a, b) |
replace every occurrence |
mkString(sep) |
join a collection into a string |
isEmpty, nonEmpty, isBlank |
emptiness checks |
Strings are collections of characters
Every collection method also works on strings, treating them as a sequence of Chars.
@main def run(): Unit =
val word = "Banana"
println(word.filter(_.isUpper))
println(word.map(_.toUpper))
println(word.distinct)
println(word.toLowerCase.groupBy(identity).view.mapValues(_.length).toList.sorted)
println(List("red", "green", "blue").mkString("[", ", ", "]"))B
BANANA
Ban
List((a,3), (b,1), (n,2))
[red, green, blue]
Comparing strings
Use == to compare text. Unlike Java, Scala's == compares content, and it is safe even when one side is null.
"abc" == "ab" + "c" // true
"abc".equalsIgnoreCase("ABC") // true
"apple" < "banana" // true (alphabetical)
"apple".compareTo("banana") // a negative numberTest yourself
Which interpolator lets you format a number as %.2f?
sfrawfmt
What does "abc" == "ab" + "c" evaluate to in Scala?
truefalse- It depends on the JVM
- A compile error
What is stripMargin used for?
- Removing trailing spaces
- Removing the leading whitespace and
|from each line of a multi-line string - Removing all newlines
- Wrapping long lines