Search code examples
scalastring-formatting

Scala String trick or method that inserts a new line or other character each time an "|" is placed


First of all I would like to apologise for how vague this question may seem, but at this point, I have not found any information on the matter.

Some time ago a colleague was talking to me about monoids and a JSON Parser, then he showed me a way of constructing Strings that looked more or less like this (Based on my poor memory):

strangeMethodOrTrick = {

  | Lorem ipsum dolor sit amet
  | consectetur adipiscing elit
  | sed do eiusmod
  | tempor incididunt

}.toString

At one point he mentioned that, every time the "|" character was typed in, it meant a line break was placed at the end of each line once the final String was created.

Apologies again for not providing more information about the subject, today I asked my colleague about this but he said he doesn't remember such thing like that or anything related to it.

For my part I haven't found any information either, I only remember what the code looked like and so far I haven't found that in the Scala documentation.

I would appreciate if anyone knows about this tactic and, if you know the name or how I could find more information about it.

For anything else, I wish you guys a very happy new year!


Solution

  • It's not a built-in feature and it doesn't insert new line breaks. The standard library provides an extension method for strings stripMargin that strips any leading whitespace followed by | from every line of a string.

    val str = 
      """|multiple lines
         |in one string
         |with stripMargin""".stripMargin
    

    Note that the newlines are already part of the string before calling stripMargin because I constructed a multi line string with the help of triple quotes """. All stripMargin does is delete the leading whitespace and the |.

    As you can see in the docs there is a stripMargin method that you can call with another character than | if you want to, e.g. stripMargin('#').