You want to create multiline strings within your Scala source code, like you can with the “heredoc” syntax of other languages.
In Scala, you create multiline strings by surrounding your text with three double quotes:
val
foo
=
"""This is
a multiline
String"""
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 String
You can solve this problem in several different ways. First, you can left-justify every line after the first line of your string:
val
foo
=
"""This is
a multiline
String"""
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 (|
):
val
speech
=
"""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:
val
speech
=
"""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:
val
speech
=
"""Four score and
|seven years ago
|our fathers"""
.
stripMargin
.
replaceAll
(
"\n"
,
" "
)
This yields:
Four score and seven years ago our fathers
Another nice feature of Scala’s multiline string syntax is that you can include single- and double-quotes without having to escape them:
val
s
=
"""This is known as a
|"multiline" string
|or 'heredoc' syntax."""
.
stripMargin
.
replaceAll
(
"\n"
,
" "
)
This results in this string:
This is known as a "multiline" string or 'heredoc' syntax.
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.