String Interpolators

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 interpolator
  • f is used for formatted output
  • raw is another
    • println(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, and raw are built in
  • Can write your own interpolators (like sql or Q)