What is the rationale behind having companion objects in Scala?

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.

Leave a Comment