1.2. Creating Multiline Strings
Problem
You want to create multiline strings within your Scala source code, like you can with the “heredoc” syntax of other languages.
Solution
In Scala, you create multiline strings by surrounding your text with three double quotes:
valfoo="""This isa multilineString"""
Discussion
Although this works, the second and third lines in this example will end up with whitespace at the beginning of their lines. If you print the string, it looks like this:
This is
a multiline
StringYou can solve this problem in several different ways. First, you can left-justify every line after the first line of your string:
valfoo="""This isa multilineString"""
A cleaner approach is to add the stripMargin method to the end of your
multiline string and begin all lines after the first line with the pipe
symbol (|):
valspeech="""Four score and|seven years ago""".stripMargin
If you don’t like using the |
symbol, you can use any character you like with the stripMargin method:
valspeech="""Four score and#seven years ago""".stripMargin('#')
All of these approaches yield the same result, a multiline string with each line of the string left justified:
Four score and seven years ago
This results in a true multiline string, with a hidden \n character after the word “and” in the first
line. To convert this multiline string into one continuous line you can
add a replaceAll method after the
stripMargin call, replacing all
newline characters with blank spaces:
valspeech="""Four ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access