Scala String Interpolation - Print And Format Variables

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

Overview

In this tutorial, we will go over String interpolation in Scala which allows us to easily print and format variables and expressions.

Make sure you have reviewed the previous tutorial on how to declare immutable variables as we will be using them here. If you do not have IntelliJ IDEA installed, please follow the tutorials from Chapter 1.

Steps

1. Using String interpolation to print a variable

Let's assume that you have a variable called favoriteDonut and would like to use the String interpolation feature in Scala to print that variable.


println("Step 1: Using String interpolation to print a variable")
val favoriteDonut: String = "Glazed Donut"
println(s"My favorite donut = $favoriteDonut")

NOTE:

  • We've prefixed the s at the beginning of our println statement.
  • We also used the dollar sign $ to refer to our variable.

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


Step 1: Using String interpolation to print a variable
My favorite donut = Glazed Donut

2. Using String interpolation on object properties

Say you have an object which represents a donut and it has name and tasteLevel properties. We can represent this donut object using a case class:


println("\nStep 2: Using String interpolation on object properties")
case class Donut(name: String, tasteLevel: String)

NOTE:

  • We've just introduced case class which is yet another feature of Scala! If you've never heard of case class before, don't worry,  we will cover it in upcoming tutorials.
  • For now you can think of case class as a means for creating domain objects where the Scala compiler does the hardwork of adding your getters and setters!
  • If you come from a Java background, think of a case class as an alternative to creating Plain Old Java Objects (POJO) but without having to write boilerplate code for getters and setters.
  • If you've used .NET, it's similar to creating domain objects but without having to define boilerplate properties for getters and setters.

To use String interpolation on the properties exposed by our object, we have to wrap our expression inside curly braces as follows:


println("\nStep 2: Using String interpolation on object properties")
case class Donut(name: String, tasteLevel: String)
val favoriteDonut2: Donut = Donut("Glazed Donut", "Very Tasty")
println(s"My favorite donut name = ${favoriteDonut2.name}, tasteLevel = ${favoriteDonut2.tasteLevel}")

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


Step 2: Using String interpolation on object properties
My favorite donut name = Glazed Donut, tasteLevel = Very Tasty

3. Using String interpolation to evaluate expressions
Similar to step 2, you can use String interpolation with expressions by using the curly braces. In the example below, we check to see if we are buying 10 donuts:


println("\nStep 3: Using String interpolation to evaluate expressions")
val qtyDonutsToBuy: Int = 10
println(s"Are we buying 10 donuts = ${qtyDonutsToBuy == 10}")

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


Step 3: Using String interpolation to evaluate expressions
Are we buying 10 donuts = true

4. Using String interpolation for formatting text
In some cases, you may want to format your strings by say pre-pending some white spaces in front of the text. This can be achieved using the f interpolation as follows:


println("\nStep 4: Using String interpolation for formatting text")
val donutName: String = "Vanilla Donut"
val donutTasteLevel: String = "Tasty"
println(f"$donutName%20s $donutTasteLevel")

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


Step 4: Using String interpolation for formatting text
       Vanilla Donut Tasty

NOTE:

  • The extra white spaces that were prepended to Vanilla Donut String.

5. Using f interpolation to format numbers
As an example, let's first print the price of one donut using the s interpolation:


println("\nStep 5: Using f interpolation to format numbers")
val donutPrice: Double = 2.50
println(s"Donut price = $donutPrice")

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


Step 5: Using f interpolation to format numbers
Donut price = 2.5

But, what if we wanted to print the 2 decimal places for the donutPrice variable. This can be achieved by using the f interpolator.


println("\nStep 5: Using f interpolation to format numbers")
val donutPrice: Double = 2.50
println(s"Donut price = $donutPrice")
println(f"Formatted donut price = $donutPrice%.2f")

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


Formatted donut price = 2.50

6. Using Raw interpolation

The raw String interpolation will allow you to print any symbols within your String. In the example below we would like to print the donut name followed by \t, as opposed to evaluating \t to tab spaces:


println("\nStep 6: Using raw interpolation")
println(raw"Favorite donut\t$donutName")

This concludes our tutorial on Scala String Interpolation - Print And Format Variables 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 article, we went over the following:

  • How to print variables using the s String interpolation.
  • How to print object properties using String interpolation.
  • How to format strings using the f String interpolation.
  • How to use the raw String interpolation

Tip

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to escape quotes in String.

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: