This question already has answers here:
Closed 7 years ago.
Possible Duplicate:
What is the rationale behind having companion objects in Scala?
Thanks for all responses to my previous post( Scala: companion objects and "new" keyword). I would like to ask you what is the general purpose of a companion object in Scala?
Firstly, could we not have included all the methods, such as apply, in the forms of contructor/method definition on the class itself?
Furthermore, what is the point of a companion Boolean object, as it does not even define apply method?
Thanks again in advance for all your responses.
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.