Scala – multi-line strings

Scala has a really awesome feature, that allows you to use multi-line strings in the language. I find this particularly helpful for SQL, or inline documentation.

val str = """
   test
"""

If you want to deal with tabbing issues, you can put a pipe at the beginning of each line. When you do this, the string out of this is stripped of the extraneous whitespace at the beginning of each line.

val str = """
  |abc
  |def
  |ghi
"""

If for some reason you dislike using a pipe for this, you can pick another character and than call stripMargin on the output, to apply the same change that the pipe would have done:

val str = """
   #test
""".stripMargin('#')

This returns the following result:

"
test
"

This is really compelling if you combine it with string interpolation, as this allows you to pull in any constants you have, or do computations within the string, for instance:

val word = "test"
val str = s"""
  ${word}
"""

And this will swap in the external variable:

"
  test
"

Like I said in the beginning – this is really useful for SQL. You might be asking how you escape values, as this is clearly necessary. While not well documented, you can put whatever you want in the ${} block, which allows you to call external functions, do computations, etc, like so:

val str = s"""
  ${word.length()}
"""

In this case it returns a value like this:

"
  4
"

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *