Start learning free

LESSON 55 OF 414 · STRINGS I

Escaping Characters in Scala: Quotes, Backslashes and Newlines

Lesson Read the full explanation

There are times when we want to use quotes inside a string. For example, suppose we want to print the message I am John "the coder" Doe:

println("I am John "the coder" Doe")

You can already see by the text color that we have a problem. Scala recognizes the string to be only I am John .

Scala finds the first quotation mark and interprets that the string starts there. But then, it finds the second quotation mark (after John ) and interprets the string ends there.

Character escaping comes to our rescue!


Escaping characters:

In Scala, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, Double quotes (") is considered a special character by Scala. Its job is to let Scala know when a string declaration starts / ends.

There is a way to print special characters like these in Scala, and that is by using the backslash character (\).

When we put \ before a special character, we tell Scala:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a Double quote, Scala no longer interprets that as being the end of the string:

println("I am John \"the coder\" Doe")

println("After \"Coding 101\" we'll solve some problems")

The output of this code is:

I am John "the coder" Doe
After "Coding 101" we'll solve some problems

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

println("C:\Users\Andy\Games")

This code looks perfectly fine at first sight, but if you run it, the compiler would reject it with errors such as invalid escape character.

When Scala sees \A or \G, it supposes that you are trying to escape the character A or G, which are not special characters thus cannot be escaped.

Now that you've learned about its function, what type of character do you think \ is in Scala? It's a special character!

And like any special character, it can also be escaped by putting another \ in front of it (\\):

println("C:\\Users\\Andy\\Games")

The output of this code is:

C:\Users\Andy\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

println("Hello world!\nWhat a good day for coding!\n")
println("Let's have a blast!")

The output of this code is:

Hello world!
What a good day for coding!

Let's have a blast!

Notice the empty line after What a good day for coding! ?

That's one new line from the \n plus the new line that println() prints no matter what the message is.


Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · STRINGS I

    Escaping Characters in Scala, explained

    Why strings need escapes

    A Scala string literal starts and ends with a double quote. That makes the double quote a special character: inside a string, it means "the string stops here". So this line can't print the message I am John "the coder" Doe:

    println("I am John "the coder" Doe")
    

    The compiler sees the string "I am John ", then the bare words the coder, then a second string starting at the next quote. The code doesn't compile.

    The fix is an escape sequence: a backslash \ followed by a character. The backslash tells the compiler to treat the next character differently from usual.

    Escaping a double quote

    Put a backslash before each quote that belongs to the text:

    println("I am John \"the coder\" Doe")
    
    println("After \"Coding 101\" we'll solve some problems")
    

    The output is:

    I am John "the coder" Doe
    After "Coding 101" we'll solve some problems
    

    The sequence \" in the source code is a single character in the string. The apostrophe in we'll needs no escape inside a double-quoted string, since only the double quote ends such a string.

    Escaping the backslash itself

    The backslash is special too, so a literal one has to be escaped. A Windows-style path shows the problem:

    println("C:\Users\Andy\Games")
    

    The compiler reads \U, \A and \G as the start of escape sequences that don't exist, and rejects the line with errors such as "invalid escape character". To get one real backslash, write two:

    println("C:\\Users\\Andy\\Games")
    
    C:\Users\Andy\Games
    

    Each \\ in the source becomes one \ in the string. The string "a\\b" has three characters, not four.

    Newlines and other escapes

    Escapes also work the other way: a backslash can give a plain letter a special meaning. \n is a newline:

    println("Hello world!\nWhat a good day for coding!\n")
    println("Let's have a blast!")
    
    Hello world!
    What a good day for coding!
    
    Let's have a blast!
    

    The empty line comes from two newlines in a row: the \n at the end of the first string, and the line break that println always adds after its argument.

    The common escape sequences are:

    SequenceMeaning
    \"a double quote
    \\a backslash
    \na new line
    \ta tab

    An alternative: triple-quoted strings

    Scala also has strings written between three double quotes. Backslashes in them are not escapes, and single double quotes inside are allowed:

    println("""C:\Users\Andy "x" """)
    println("""say "hi"""")
    
    C:\Users\Andy "x" 
    say "hi"
    

    Notice the space before the closing quotes in the first line: three quotes in a row end the string, so a string can't finish with a quote of its own unless something sits in between. The exercises in this lesson use ordinary strings with escapes.

    The exercise

    The lesson has three steps, each a single println:

    1. Quotes. Print I'll study "Coding 101" on AlgoCademy. Escape the two double quotes around Coding 101. The apostrophe in I'll stays as it is.
    2. Two lines from one println. Print I will learn this and No matter what on separate lines by putting \n between them.
    3. A path. Print C:\Users\Andy\notion, doubling every backslash.

    Here are the three lines together:

    println("I'll study \"Coding 101\" on AlgoCademy")
    println("I will learn this\nNo matter what")
    println("C:\\Users\\Andy\\notion")
    

    The output:

    I'll study "Coding 101" on AlgoCademy
    I will learn this
    No matter what
    C:\Users\Andy\notion
    

    Common mistakes

    • Forward slash instead of backslash. /" is not an escape; only \ starts one.
    • Escaping the apostrophe. There is no need inside double quotes. Keep the text as it is.
    • Single backslash in a path. The line fails to compile. Every backslash in the printed text needs a partner.
    • Counting the extra blank line. A trailing \n plus println prints an empty line. Add a trailing \n only if you want that.
    • Space after the backslash. The backslash must touch the character it escapes.

    Key takeaways

    • A backslash starts an escape sequence inside a string.
    • \" prints a double quote, \\ prints a backslash, \n starts a new line.
    • The source text of an escape is longer than the character it produces.
    • println always adds its own line break.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free