Scala companion objects

Companion objectsare a specific type ofobject.

Just like theobjectwe saw in the previous SKB,companion objectdoes not need to be instantiated.

The source of the main difference betweenobjectandcompanion objectcomes from the name that they share with aclass.

Did you notice that theclassnamedAnimalis able to call a method namedconvertLegNumberToNamethat is defined asprivate?

Other thing to notice is theimport. In the previous SKB related toobject, we learned how to call the member of anobjectusing its name. When you use theimport, you do not need to use the name anymore. Inside the context, where theimportis used, with theAnimal._, the name is not needed to be called.

To summarize, acompanion objectis exactly like an object, except that theclassthat share the same name can access theprivatemembers.

It is commonly used when you need to have constant or helper methods related to this class.

Leaving those members inside the class can create memory issues. Let's say you have a large constant – maybe an array or some other complex object. If it is stored inside theclass, then each instantiation will make a copy of this constant in the memory. If instead the constant is in thecompanion object, then the program will only have to create the constant once.

Reveal more information and clues
Load Exercise