Scala singletons

Scala has singleton objects called companion objects. A companion object is an object with the same name as a class. A companion object also can access private methods and fields of its companion class. Both a class and its companion object must be defined in the same source file. The companion object is where the apply() factory method may be defined. Let's have a look at the following example of a companion class:

class Singleton {  // Companion class
  def m() {
    println("class")
  }         
}

And then its companion object as:

object Singleton { // Companion Object
  def m() {
    println("companion")
  }         
}

It is that simple, when a case class is defined, Scala automatically generates a companion object for it.

The apply() factory method

If a companion ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.