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 object defines an apply()
method, the Scala compiler calls it when it sees the class name followed by ()
. So, for example, when Scala sees something like:
Singleton(arg1...