Learn Scala 3 Fast: Multiline Strings

The second extra thing to know about the Scala String type is that you can create multiline strings by using """ instead of " when creating the string:

val address = """
    Alvin Alexander
    123 Main Street
    Talkeetna, AK 99676
"""

This works fine, but it’s important to note that this creates a multiline string with leading spaces in it:

    Alvin Alexander
    123 Main Street
    Talkeetna, AK 99676

A technique you can use to remove those leading spaces is to begin each line with the | symbol, and then add the stripMargin method at the end of the string:

val address = """
    |Alvin Alexander
    |123 Main Street
    |Talkeetna, AK 99676
""".stripMargin

This left-justifies the string, so when you print it, it now looks like this:

Alvin Alexander
123 Main Street
Talkeetna, AK 99676

In that code, stripMargin is a method that’s available on instances of the Scala String class. It was created for this situation, and by default it expects the | symbol to be used to begin each line. You can also specify a different character, if you prefer:

val address = """
    #Alvin Alexander
    #123 Main Street
    #Talkeetna, AK 99676
""".stripMargin('#')

In that example I use the # character to begin each line, and then specify that character by calling stripMargin('#').

Multiline strings and interpolators

Multiline strings are just strings — they are of the String data type — so they can also be used with interpolators:

val address = s"""
    |$name
    |$street
    |$city, $state $zip
""".stripMargin

Exercises

The exercises for this lesson are available here.