Scala multiline strings (heredoc) syntax

Scala FAQ: Can I create multiline strings in Scala, using something like a heredoc syntax?

Back to top

Multiline string examples

Technically Scala doesn't refer to it as a “heredoc” syntax, but you can easily create multiline strings in Scala. All you have to do is enclose each end of your multiline string in three double-quotes, like this:

val foo = """Line 1.
Line 2.
Line 3."""

Here's an example of what this multiline string syntax looks like in a small example Scala application:

object MultilineStrings {

  def main(args: Array[String]) {
    val foo = """Line 1.
Line 2.
Line 3."""
    println(foo)
  }

}

As you might guess from the way I've left-justified the second and third strings, Scala will put any leading spaces into those strings, so this multiline string:

// no leading spaces on 2nd and 3rd lines
val foo = """Line 1.
Line 2.
Line 3."""

will be different than this one:

// has leading spaces on 2nd and 3rd lines
val foo = """Line 1.
             Line 2.
             Line 3."""

That being said ...

Back to top

Stripping the spaces off of Scala multiline strings

You can use a method named stripMargin to make multiline strings look the way you want them to look without having to worry about spacing. Just precede each line with a | character, like this:

val s = """
  |Line 1.
  |Line 2.
  |Line 3.""".stripMargin

That use of stripMargin creates a string like this (including a leading blank line):

Line 1.
Line 2.
Line 3.

Of course there are a lot of things you can do to get rid of blank lines. One thing I do from time to time is to convert multiline strings to single-line strings, with code like this:

val s = """
  |Line 1.
  |Line 2.
  |Line 3.""".stripMargin.replaceAll("\n", " ")

This creates a string that looks like this:

 Line 1. Line 2. Line 3.

Again, that string has a leading space, but it's easy to get rid of it.

As a final note about stripMargin, you can use other characters with it besides the | character; that character is just the default. For instance, this is how you would use the # character instead of the default | character:

val s = """
  #Line 1.
  #Line 2.
  #Line 3.""".stripMargin('#')

You can then trim off any blank spaces as usual.

Back to top

Summary

In Scala -- and other programming languages -- I've found that multiline strings can make your code look pretty ugly, so if I use them, I tend to put them in a separate file, but from time to time, having the ability to create multiline strings is nice, and I appreciate that this functionality is in Scala.

Back to top

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.