Scala FAQ: Can I create multiline strings in Scala, using something like a heredoc syntax?
Technically Scala doesn't refer to it as a heredoc syntax, but you can easily create multiline strings in Scala. All you have to do is enclose each end of your multiline string in three double-quotes, like this:
val foo = """Line 1. Line 2. Line 3."""
Here's an example of what this multiline string syntax looks like in a small example Scala application:
object MultilineStrings {
def main(args: Array[String]) {
val foo = """Line 1.
Line 2.
Line 3."""
println(foo)
}
}
As you might guess from the way I've left-justified the second and third strings, Scala will put any leading spaces into those strings, so this multiline string:
// no leading spaces on 2nd and 3rd lines val foo = """Line 1. Line 2. Line 3."""
will be different than this one:
// has leading spaces on 2nd and 3rd lines
val foo = """Line 1.
Line 2.
Line 3."""
In Scala -- and other programming languages -- I've found that multiline strings can make your code look pretty ugly, so if I use them, I tend to put them in a separate file, but from time to time, having the ability to create multiline strings is nice, and I appreciate that this functionality is in Scala.
Post new comment