Scala - How To Escape Characters And Create Multi-line String

By Nadim Bahadoor | Last updated: March 16, 2018 at 11:17 am

Overview

In this tutorial, we will show how to escape characters when writing text. In addition, we will learn how to format multi-line text so that it is more readable.

 

Make sure that you have followed the tutorials from Chapter 1 on how to install and use IntelliJ IDEA. Don't forget to also review the tutorials from Chapter 2 as we will build on what we've previously learned.

Steps

 1. How to escape a Json String

In tutorial How To Declare Variables And Types, we learned the syntax to create and assign an immutable String variable. Let's assume that you have a JSON String which represents a donut object with properties donut_name, taste_level and price.

How would you define a variable to store the donut JSON String?


println("Step 1: How to escape a Json String")
val donutJson: String ="{"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}"

NOTE:

  • The Scala compiler will complain about the double quotes in the JSON field names.

2. Using backslash to escape quotes

If you have used another programming language like Java or .NET in the past, you would be familiar with escaping quotes in a String using backslash \


println("\nStep 2: Using backslash to escpae quotes")
val donutJson2: String ="{\"donut_name\":\"Glazed Donut\",\"taste_level\":\"Very Tasty\",\"price\":2.50}"
println(s"donutJson2 = $donutJson2")




You will see the output below when you run your Scala application in IntelliJ:


Step 2: Using backslash to escpae quotes
donutJson2 = {"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}

NOTE:

  • As you can see from above, we were able to print a JSON String by making use of backslash \
  • This is great but if you have longer text to escape, I'm sure you will get bored quite quickly : ) by having to escape each and every individual quote within your JSON String. So, let's see how to make this easier in Step 3 below.

3. Using triple quotes """ to escape characters

Fortunately Scala has a much better solution! To help you easily escape characters and symbols inside strings, you just need to wrap the text within triple quotes """<YOUR TEXT TO ESCAPE>""" as follows:


println("\nStep 3: Using triple quotes \"\"\" to escape characters")
val donutJson3: String = """{"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}"""
println(s"donutJson3 = $donutJson3")

You will see the output below when you run your Scala application in IntelliJ:


Step 3: Using triple quotes """ to escape characters
donutJson3 = {"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}

4. Creating multi-line text using stripMargin

As we've just seen in Step 3, using """ should be a clear winner on escaping quotes and other symbols! But, programmers in today's world demand much more :)

What if you would like to indent your text so that it's more readable? Look no further, Scala is here to help with the use of stripMargin:


val donutJson4: String =
    """
      |{
      |"donut_name":"Glazed Donut",
      |"taste_level":"Very Tasty",
      |"price":2.50
      |}
      """
   .stripMargin

You will see the output below when you run your Scala application in IntelliJ:


Step 4:  Creating multi-line text using stripMargin
donutJson4 = 
{
"donut_name":"Glazed Donut",
"taste_level":"Very Tasty",
"price":2.50
}

This concludes our tutorial on Scala - How To Escape Characters and Create Multi-Line String and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to assign a JSON String to a val.
  • How to escape characters in a String using backslash
  • How to escape characters using triple quotes
  • How to create multi-line text using stripMargin

Tip

  • You can refer to the Scala API documentation to find more details about some function. If you look at the definition of the stripMargin function, you will see that it also takes in a parameter to allows you to specify a different character other than the default pipe |

println("\nTip: stripMargin using a different character")
val donutJson5: String =
"""
#{
#"donut_name":"Glazed Donut",
#"taste_level":"Very Tasty",
#"price":2.50
#}
""" .stripMargin('#')
println(s"donutJson5 = $donutJson4")

Source Code

The source code is available on the allaboutscala GitHub repository.

What's Next

In the next tutorial, I will go over how Scala is able to infer the types of our variables.


Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: