String Interpolators (Scala 3 Video)
This is the third of three lessons on the Scala String
data type.
String interpolators:
- Use to put variables and expressions in strings
- Use to create a String
- Use when printing information
- Use instead of
+
(adding things to strings)
val fname = "Alvin"
val lname = "Alexander"
val fullName = fname + " " + lname // don't do
val fullName = s"$fname $lname"
When you have expressions in strings, use {}
:
// example:
val rez = s"${1 + 1}"
// example:
case class Person(firstName: String, lastName: String)
val p = Person("Alvin", "Alexander")
val fullName = s"${p.firstName} ${p.lastName}"
Other interpolators
- The beauty of this is the consistency
s
is the main interpolatorf
is used for formatted outputraw
is anotherprintln(raw"foo\nbar")
prints"foo\nbar"
Here’s an example of f
:
val name = "Fred"
val age = 33
val weight = 200.00
s"$name is $age years old, and weighs $weight pounds."
f"$name is $age years old, and weighs $weight%.2f pounds."
Write your own interpolator
Summary
- Use
s""
and not+
- Use
{}
to enclose expressions s
,f
, andraw
are built in- Can write your own interpolators (like
sql
orQ
)
Update: All of my new videos are now on
LearnScala.dev