Unindent: Sane Multi-Line String Literals for Scala

Written by Dave Gurnell

Unindent is a tiny library for creating indent-adjusted multi-line String literals in Scala. Say goodbye to trim and stripMargin!


Scala’s bare-bones multi-line String literals don’t account for whitespace on the left of a line:

val longString =
  """
  This string has
  extraneous whitespace.
  """
// longString: String = "This string has\n  extraneous whitespace."

The conventional way around this is to use the trim and stripMargin methods to fix the problem at runtime, which is clearly ludicrous:

val whaaaaat =
  """
  |This string has
  |no extraneous whitespace.
  """.trim.stripMargin
// whaaaaat: String = "This string has\nno extraneous whitespace."

Unindent brings sanity to the situation by providing an i"" string prefix that trims leading whitespace at compile time:

import unindent._

val muchBetter =
  i"""
  This string is
  whitespace free.
  """
// muchBetter: String = "This string is\nwhitespace free."

Whitespace is only trimmed if it is shared by all lines in the literal, so you can still indent lines relative to each other:

import unindent._

val pythonCode =
  i"""
  def add(a, b):
      return a + b
  """
// pythonCode: String = "def add(a, b):\n    return a + b"

For convenience, i"" supports the same interpolation semantics as s"":

import unindent._

val name = "Dave"

val greeting = i"""
  Hello $name.
  I unindented this for you.
  """
// greeting: String = "Hello Dave.\nI unindented this for you."

UPDATE: You can grab Unindent via SBT. Check the README on GitHub for details.