Scala String – Multiline Escape

Scala supports a multi-line escape: “”” – yes, that’s 3 double quotes.

Here’s an example of setting a String to a multiline value.

object Welcome extends App {
  val welcome = """Hello, World!
    How are you today?"""
  println(welcome)
}

Output:

Hello, World!
    How are you today?

This is okay, but to produce the desired output we need to trim the second line. We can do this with a pipe to mark the start of the next line and call the stripMargin function. Here’s an example:

object Welcome extends App {
  val welcome = """Hello, World!
    |How are you today?"""
  println(welcome.stripMargin)
}

Output:

Hello, World!
How are you today?

The double quotes simplify adding multiline String literals – maybe still a bit ugly but not as bad as the Java equivalent. The stripMargins is really just so the added lines can still be indented and the code will format correctly. A nice little touch 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s