Companion objects are needed to:
- declare methods related to the companion's class which would otherwise be static (unlike in Java, you cannot declare a static method within the class itself in Scala)
- declare the
unapply
and unapplySeq
methods to define custom extractors for pattern matching (see here)
- declare the
apply
method which is typically used as a factory method that creates objects of the particular class (but doesn't have to be)
- companion objects can access private fields and methods of their companion trait/class - useful for creating static operations on that particular trait/class
- they are important for the implicit resolution -- when looking for an implicit value of a certain type, the companion object of that type is inspected to see if there exists a corresponding
implicit
definition; see the exact rules of implicit resolution in the Scala specification or a short summary in this blog post
The Boolean
object in the Scala standard library provides the methods box
and unbox
used to convert between primitive booleans and their wrapped, object representations. It is additionally (currently) used as an argument to the @specialized
annotation, to denote on which primitive types the class needs to be specialized on.