How to add new line Scala?
In this article, we will learn how to add a new line in Scala.
1. Using the newline character (\n):
This is the most straightforward approach. The \n character represents a newline and will be interpreted as such when the string is printed.
// Creating object
object GfG {
// Main method
def main(args: Array[String]) {
// Defining a string
val message = "This is the first line.\nThis is the second line."
// Printing the string
println(message)
}
}
Output:
This is the first line.
This is the second line.
2. Using triple-quoted strings:
// Creating object
object GfG {
// Main method
def main(args: Array[String]) {
// Defining a string
val message = """This is
a multi-line
string"""
// Printing the string
println(message)
}
}
Output:
This is
a multi-line
string
Although this works, the second and third lines in this example will end up with whitespace at the beginning of their lines.
You can solve this problem in several different ways. First, you can left-justify every line after the first line of your string:
// Creating object
object GfG {
// Main method
def main(args: Array[String]) {
// Defining a string
val message = """This is
a multi-line
string"""
// Printing the string
println(message)
}
}
Output:
This is
a multi-line
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 (|). This method removes any leading whitespace before the | character, making the output cleaner.
// Creating object
object GfG {
// Main method
def main(args: Array[String]) {
// Defining a string
val message = """This is the first line.
|This is the second line.""".stripMargin
// Printing the string
println(message)
}
}
Output:
This is the first line.
This is the second line.
You can use any character as a delimiter with stripMargin. For example:
// Creating object
object GfG {
// Main method
def main(args: Array[String]) {
// Defining a string
val message = """This is the first line.
#This is the second line.""".stripMargin('#')
// Printing the string
println(message)
}
}
This will give the same output as above.