What is the rationale behind having companion objects in Scala?

Rahul picture Rahul · Mar 4, 2009 · Viewed 32.8k times · Source

Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say Foo and also create a companion object for it?

Answer

Saem picture Saem · Mar 4, 2009

The companion object basically provides a place where one can put "static-like" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.

Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example, Foo and FooFactory everywhere, you can have a class with a companion object take on the factory responsibilities.