String interpolation in Scala
Three interpolators: s for values, f for formatted output, raw for untouched escapes.
val bookTitle = "Piranesi"
val members = 7
val averageRating = 4.36
// s"..." splices a value; use ${...} for a whole expression.
val blurb = s"$bookTitle has $members readers"
val spotsLine = s"Room for ${12 - members} more"
// f"..." adds format specifiers and checks them while compiling.
val scoreLine = f"$bookTitle%s scored $averageRating%.1f"
val paddedLine = f"$members%3d copies on hand"
// raw"..." leaves escapes alone: the \n in \north stays literal.
val shelfPath = raw"shelves\north\fiction"
def showBook(): Unit =
println(blurb)
println(spotsLine)
println(scoreLine)
println(paddedLine + " " + shelfPath)
How it works
s"$bookTitle has $members readers"splices two values, and${12 - members}wraps a whole expression.f"$bookTitle%s scored $averageRating%.1f"rounds to one decimal, andf"$members%3d copies on hand"pads to three columns.raw"shelves\north\fiction"leaves the escape alone, so\nstays two characters.
Keywords and builtins used here
UnitdefshowBookval
The run, in numbers
- Lines
- 20
- Characters to type
- 623
- Tokens
- 88
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 70 seconds.
Step 3 of 3 in Values & types, step 3 of 27 in Language basics.