Creating Multiline Strings
In the following lesson, you will learn how to create multiline strings in Scala.
Problem
Imagine there’s a very long piece of text that you want the compiler to print. Or you have a list of items which need to be displayed vertically, item by item to make them easier to read. How would you go about creating multiple lines (multiline strings) within one string?
Solution
From what we have already discussed, escape characters come to mind. \n is used to escape the line and take all the characters after it to the next line. Let’s try it.
While the above code does give us the desired output, it is extremely tedious to insert \n at every point where we want to move to the next line. Also, the code is difficult to read; can you imagine how messy it would look if we have a paragraph?
Fortunately, Scala has a much more efficient way of creating multiline strings. To do so, you simply write your string as you want to print it and surround it with three double quotation marks.
Syntax
Let’s map our multiline string example on the syntax above.
The above code is not only easier to write, but easier to read as well.
In the next lesson, we will learn how to split strings in Scala.