Scala Tutorial - Learn How To Declare And Use Singleton Object

By Nadim Bahadoor | Last updated: March 16, 2018 at 13:14 pm

Overview

In this tutorial, we will learn how to declare Singleton Object which you can use to store global fields and utility functions or methods.

 

What is a Singleton Object?

As per Wikipedia, the Singleton Pattern is a a fairly common design pattern when you need exactly one instance of an object.

 

The Singleton Pattern is so commonly used that Scala has made it very easy to create single instances of an object. All you need to do is to make use of the keyword object as we will show in the steps below.

Steps

1. How to declare a Singleton Object

In the previous tutorials, we've actually made use of Singleton Objects without even mentioning it! So as a reminder, to create Singleton Objects in Scala, you need to make use of the keyword object as shown below.


println("Step 1: How to declare a Singleton Object")
object DonutShoppingCartCalculator {

}

2. How to define a global field

If you have used another programming language such as Java or .NET, you would perhaps expect that Scala also has the keyword static which would allow you to declare global fields and constants.

 

But, Scala does not have a static keyword! Instead, you can simply encapsulate a global field using the val keyword inside a Singleton Object.


println("Step 1: How to declare a Singleton Object")
object DonutShoppingCartCalculator {

 println("\nStep 2: How to define a global field")
 val discount: Double = 0.01
}

NOTE:

  • Perhaps in a real application, you would not hard-code a discount value. But, we're just showing here how to expose a discount field globally.

3. How to define utility function called calculateTotalCost

Once again as mentioned in Step 2 above, Scala does not exposed a static keyword. But you can encapsulate functions and methods inside a Singleton Object if you would like to expose some globally accessible utility function or method.


println("Step 1: How to declare a Singleton Object")
object DonutShoppingCartCalculator {

 println("\nStep 2: How to define a global field")
 val discount: Double = 0.01

 println("\nStep 3: How to define utility function called calculateTotalCost")
 def calculateTotalCost(donuts: List[String]): Double = {
  // calculate the cost of donuts
  return 1
 }
}

NOTE:

  • In a real application, the calculateTotalCost() function would have other parameters required to calculate the total cost of donuts in a shopping cart.
  • You can always review the tutorials on functions if you are unclear about how to create and use functions in Scala.

4. How to call global discount field from Step 2

To access a global field, you simply call the Singleton Object with the dot operator and followed by the global field.


println("\nStep 4: How to call global discount field from Step 2")
println(s"Global discount = ${DonutShoppingCartCalculator.discount}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to call global discount field from Step 2
Global discount = 0.01

 

5. How to call the utility function calculateTotalCost from Step 3

To access a global utility function or method, you simply call the Singleton Object with the dot operator and followed by the utility function or method.


println("\nStep 5: How to call the utility function calculateTotalCost from Step 3")
println(s"Call to calculateTotalCost function = ${DonutShoppingCartCalculator.calculateTotalCost(List())}")

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to call the utility function calculateTotalCost from Step 3
Call to calculateTotalCost function = 1.0

This concludes our tutorial on Learn How To Declare And Use Singleton Object 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 declare a Singleton Object
  • How to define a global field
  • How to define utility function
  • How to call global field
  • How to call the utility function or method

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 create and use case classes in Scala.

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: