Introduction
String interpolation provides a way to use variables inside strings. For instance:
val name = "James"
val age = 30
println(s"$name is $age years old") // "James is 30 years old"
Using string interpolation consists of putting an s
in front of your string
quotes, and prefixing any variable names with a $
symbol.
Other interpolators
The s
that you place before the string is just one possible interpolator that Scala
provides.
Scala provides three string interpolation methods out of the box: s
, f
and raw
.
Further, a string interpolator is just a special method, so it is possible to define your
own. For instance, some database libraries define a sql
interpolator that returns a
database query.
The s
Interpolator (s
-Strings)
Prepending s
to any string literal allows the usage of variables directly in the string. You’ve already seen an example here:
val name = "James"
val age = 30
println(s"$name is $age years old") // "James is 30 years old"
Here, the $name
and $age
placeholders in the string are replaced by the results of
calling name.toString
and age.toString
, respectively. The s
-String will have
access to all variables that are currently in scope.
While it may seem obvious, it’s important to note here that string interpolation will not happen in normal string literals:
val name = "James"
val age = 30
println("$name is $age years old") // "$name is $age years old"
String interpolators can also take arbitrary expressions. For example:
println(s"2 + 2 = ${2 + 2}") // "2 + 2 = 4"
val x = -1
println(s"x.abs = ${x.abs}") // "x.abs = 1"
Any arbitrary expression can be embedded in ${}
.
For some special characters, it is necessary to escape them when embedded within a string.
To represent an actual dollar sign you can double it $$
, like here:
println(s"New offers starting at $$14.99") // "New offers starting at $14.99"
Double quotes also need to be escaped. This can be done by using triple quotes as shown:
println(s"""{"name":"James"}""") // `{"name":"James"}`
Finally, all multi-line string literals can also be interpolated
println(s"""name: "$name",
|age: $age""".stripMargin)
This will print as follows:
name: "James"
age: 30
The f
Interpolator (f
-Strings)
Prepending f
to any string literal allows the creation of simple formatted strings, similar to printf
in other languages. When using the f
interpolator, all variable references should be followed by a printf
-style format string, like %d
. Let’s look at an example:
val height = 1.9d
val name = "James"
println(f"$name%s is $height%2.2f meters tall") // "James is 1.90 meters tall"
The f
interpolator is typesafe. If you try to pass a format string that only works for integers but pass a double, the compiler will issue an
error. For example:
val height: Double = 1.9d
scala> f"$height%4d"
<console>:9: error: type mismatch;
found : Double
required: Int
f"$height%4d"
^
val height: Double = 1.9d
scala> f"$height%4d"
-- Error: ----------------------------------------------------------------------
1 |f"$height%4d"
| ^^^^^^
| Found: (height : Double), Required: Int, Long, Byte, Short, BigInt
1 error found
The f
interpolator makes use of the string format utilities available from Java. The formats allowed after the %
character are outlined in the
Formatter javadoc. If there is no %
character after a variable
definition a formatter of %s
(String
) is assumed.
Finally, as in Java, use %%
to get a literal %
character in the output string:
println(f"3/19 is less than 20%%") // "3/19 is less than 20%"
The raw
Interpolator
The raw interpolator is similar to the s
interpolator except that it performs no escaping of literals within the string. Here’s an example processed string:
scala> s"a\nb"
res0: String =
a
b
Here the s
string interpolator replaced the characters \n
with a return character. The raw
interpolator will not do that.
scala> raw"a\nb"
res1: String = a\nb
The raw interpolator is useful when you want to avoid having expressions like \n
turn into a return character.
In addition to the three default string interpolators, users can define their own.
Advanced Usage
The literal s"Hi $name"
is parsed by Scala as a processed string literal.
This means that the compiler does some additional work to this literal. The specifics
of processed strings and string interpolation are described in SIP-11, but
here’s a quick example to help illustrate how they work.
Custom Interpolators
In Scala, all processed string literals are simple code transformations. Anytime the compiler encounters a processed string literal of the form:
id"string content"
it transforms it into a method call (id
) on an instance of StringContext.
This method can also be available on implicit scope.
To define our own string interpolation, we need to create an implicit class (Scala 2) or an extension
method (Scala 3) that adds a new method to StringContext
.
As a trivial example, let’s assume we have a simple Point
class and want to create a custom interpolator that turns p"a,b"
into a Point
object.
case class Point(x: Double, y: Double)
val pt = p"1,-2" // Point(1.0,-2.0)
We’d create a custom p
-interpolator by first implementing a StringContext
extension
with something like:
implicit class PointHelper(val sc: StringContext) extends AnyVal {
def p(args: Any*): Point = ???
}
Note: It’s important to extend AnyVal
in Scala 2.x to prevent runtime instantiation on each interpolation. See the value class documentation for more.
extension (sc: StringContext)
def p(args: Any*): Point = ???
Once this extension is in scope and the Scala compiler encounters p"some string"
, it
will process some string
to turn it into String tokens and expression arguments for
each embedded variable in the string.
For example, p"1, $someVar"
would turn into:
new StringContext("1, ", "").p(someVar)
The implicit class is then used to rewrite it to the following:
new PointHelper(new StringContext("1, ", "")).p(someVar)
StringContext("1, ","").p(someVar)
As a result, each of the fragments of the processed String are exposed in the
StringContext.parts
member, while any expressions values in the string are passed in
to the method’s args
parameter.
Example Implementation
A naive implementation of our Point interpolator method might look something like below,
though a more sophisticated method may choose to have more precise control over the
processing of the string parts
and expression args
instead of reusing the
s
-Interpolator.
implicit class PointHelper(val sc: StringContext) extends AnyVal {
def p(args: Double*): Point = {
// reuse the `s`-interpolator and then split on ','
val pts = sc.s(args: _*).split(",", 2).map { _.toDoubleOption.getOrElse(0.0) }
Point(pts(0), pts(1))
}
}
val x=12.0
p"1, -2" // Point(1.0, -2.0)
p"${x/5}, $x" // Point(2.4, 12.0)
extension (sc: StringContext)
def p(args: Double*): Point = {
// reuse the `s`-interpolator and then split on ','
val pts = sc.s(args: _*).split(",", 2).map { _.toDoubleOption.getOrElse(0.0) }
Point(pts(0), pts(1))
}
val x=12.0
p"1, -2" // Point(1.0, -2.0)
p"${x/5}, $x" // Point(2.4, 12.0)
While string interpolators were originally used to create some form of a String, the use
of custom interpolators as above can allow for powerful syntactic shorthand, and the
community has already made swift use of this syntax for things like ANSI terminal color
expansion, executing SQL queries, magic $"identifier"
representations, and many others.