This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). This is Recipe 6.5, “How to implement the Singleton Pattern with a Scala object.”
Problem
You want to create a Singleton object to ensure that only one instance of a class exists. (That is, you want to implement the Singleton Pattern in Scala.)
Solution
Create Singleton objects in Scala with the object
keyword. For instance, you might create a Singleton object to represent something like a keyboard, mouse, or perhaps a cash register in a pizza restaurant:
object CashRegister { def open { println("opened") } def close { println("closed") } }
With CashRegister
defined as an object, there can be only one instance of it, and its methods are called just like static methods on a Java class:
object Main extends App { CashRegister.open CashRegister.close }
This pattern is also common when creating utility methods, such as this DateUtils
object:
import java.util.Calendar import java.text.SimpleDateFormat object DateUtils { // as "Thursday, November 29" def getCurrentDate: String = getCurrentDateTime("EEEE, MMMM d") // as "6:20 p.m." def getCurrentTime: String = getCurrentDateTime("K:m aa") // a common function used by other date/time functions private def getCurrentDateTime(dateTimeFormat: String): String = { val dateFormat = new SimpleDateFormat(dateTimeFormat) val cal = Calendar.getInstance() dateFormat.format(cal.getTime()) } }
Because these methods are defined in an object
instead of a class
, they can be called in the same way as a static method in Java:
scala> DateUtils.getCurrentTime res0: String = 10:13 AM scala> DateUtils.getCurrentDate res1: String = Friday, July 6
Singleton objects also make great reusable messages when using actors. If you have a number of actors that can all receive start and stop messages, you can create Singletons like this:
case object StartMessage case object StopMessage
You can then use those objects as messages that can be sent to actors:
inputValve ! StopMessage outputValve ! StopMessage
See Chapter 13, Actors and Concurrency for more examples of this approach.
Discussion
In addition to creating objects in this manner, you can give the appearance that a class has both static and non-static methods using an approach known as a “companion object.” See the following recipe for examples of that approach.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |