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:
unapply
and unapplySeq
methods to define custom extractors for pattern matching (see here)apply
method which is typically used as a factory method that creates objects of the particular class (but doesn't have to be)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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With