home search about rss feed twitter ko-fi

Objects: Singletons, Part 1 (Scala 3 Video)

In Scala, an object is a class that has exactly one instance. So there’s a little magic under the hood that makes sure there is only ever one instance of this class in the system at any time.

There are three ways we use objects in Scala

  • Singleton objects
  • Companion objects
  • apply methods (which are factory methods, similar to constructors)

In this video I demonstrate how to use them as Singleton objects, and I show both one possible Singleton use, and also how to create what I call “utility objects.”

Singleton objects

A Singleton object is something like modeling a cash register in a point-of-sales application, where each monitor or display can have one and only one cash register:

object CashRegister:
    def open() = println("opened")
    def close() = println("closed")

In the real world you might want to monitor the use of the cash register. To keep this simple, let’s just say that we want to monitor how many times it’s opened and closed:

object CashRegister:

    // two private counters that cannot be accessed directly
    private var numOpens = 0
    private var numCloses = 0

    // two methods related to physically opening and closing
    // the register drawer
    def open() =
        // in the real world, here you would do whatever
        // is needed to open the register drawer
        numOpens += 1
    def close() =
        // assume that you got a signal here that the register
        // drawer was closed
        numCloses += 1

    // "getter" methods for the private variables
    def getNumberOfOpens = numOpens
    def getNumberOfCloses = numCloses

That object can then be used like this:

CashRegister.open()
CashRegister.close()
CashRegister.getNumberOfOpens     // 1
CashRegister.getNumberOfCloses    // 1

Update: All of my new videos are now on
LearnScala.dev