Strings and interpolation
A Scala string is a java.lang.String, so every method of the Java class is there, and the standard library adds about a hundred more through an implicit conversion. On top of the literal, Scala puts interpolators: a prefix in front of the quote decides how the parts inside are read.
s, f and raw
s"..." substitutes a name or an expression, f"..." substitutes and formats, and raw"..." switches the escapes off:
strings.scala
@main def strings(): Unit =
val name = "Scala"
val version = 3
println(s"$name $version")
println(s"next: ${version + 1}")
println(f"${1.0 / 3}%.3f")
println(raw"a\nb")
println("""line one
|line two""".stripMargin)
println("Ada,Linus,Grace".split(",").toList)
println(" padded ".trim)
println("abc".reverse)
println("hello".capitalize)
scala-cli run --server=false strings.scala
Scala 3
next: 4
0.333
a\nb
line one
line two
List(Ada, Linus, Grace)
padded
cba
Hello
A bare $name stops at the first character that cannot be part of a name, so an expression after the name needs braces: ${version + 1}. The format string takes the conversion of java.util.Formatter — %.3f here — and a mismatch is a compile error, not a runtime one. raw keeps the backslash, which is how a Windows path or a regular expression is written without doubling every backslash.
Triple quotes and stripMargin
A triple-quoted string spans lines and takes every character literally, quotes included. The | at the start of each line is not part of the string: stripMargin removes it together with the indentation before it, so a block of text keeps its shape in the source and loses the layout at run time.
An interpolator works in front of a triple quote too: s"""...""" substitutes in a block of lines, which is how a template or a query is written. The compiler reads a quote inside the triple quotes without an escape, which is what makes a block of text keep its shape.
The string methods
A character is a Char, which is a value of its own and converts to its numeric code. The methods below are the ones a first program reaches for:
chars.scala
@main def chars(): Unit =
val letter = 'S'
println(letter)
println(letter.toInt)
println("Scala".head)
println("Scala".tail)
println("Scala".length)
scala-cli run --server=false chars.scala
S
83
S
cala
5
head and tail throw on an empty string, so a program that may get one uses headOption and drop(1); the list lesson shows the same pair on a collection. A single quote is a Char literal and takes exactly one character, so 'ab' does not compile.
Related
- Numbers: the types an interpolated value can have.
- Methods and parameters: the methods this lesson calls.
- Arrays and ranges: the collections behind split and toList.
- Java: the String class underneath.
Article author: Arthur Isaev