Strings
Prerequisites: Data types
String interpolation
@main def interpolation(): Unit =
val name = "Ada"
val age = 36
val price = 1234.5
println(s"$name is $age years old")
println(s"Next year: ${age + 1}")
println(s"Name has ${name.length} letters")
println(f"Price: $price%.2f")
println(f"$name%-6s|$age%5d|")
println(raw"Path: C:\temp\new")
Ada is 36 years old
Next year: 37
Name has 3 letters
Price: 1234.50
Ada | 36|
Path: C:\temp\new
s"..."— inserts$name, or any expression in${ }.f"..."— adds printf-style formats after a value:%.2f(2 decimals),%5d(width 5),%-6s(left-aligned, width 6). It's type-checked:%dwith aStringis a compile error.raw"..."— no escape processing, so\tand\nstay as written.
Common methods
@main def stringMethods(): Unit =
val text = " Hello, Scala World "
val t = text.trim
println(t)
println(t.toUpperCase)
println(t.length)
println(t.replace("World", "Friends"))
println(t.split(", ").toList)
println(t.contains("Scala"))
println(t.startsWith("Hello"))
println(t.substring(7, 12))
println(t.reverse)
println("ha" * 3)
Hello, Scala World
HELLO, SCALA WORLD
18
Hello, Scala Friends
List(Hello, Scala World)
true
true
Scala
dlroW alacS ,olleH
hahaha
Scala's String is Java's String, with extra methods added — like
reverse, *, and all the collection operations (a string is a sequence
of characters).
Multi-line strings
@main def multiline(): Unit =
val message =
"""Dear Ada,
|Thanks for signing up.
|The Scala team""".stripMargin
println(message)
Dear Ada,
Thanks for signing up.
The Scala team
Triple quotes allow line breaks; stripMargin removes the indentation up
to each |, so the text can be indented with the code.
Comparing strings
In Scala, == compares contents (unlike Java, where it compares
references):
@main def compare(): Unit =
val a = "scala"
val b = "SCALA".toLowerCase
println(a == b)
println(a.equalsIgnoreCase("Scala"))
println("apple" < "banana")
true
true
true