Companion object
A class can have a companion object. It must be declared in the same file as the class, using the keyword object followed by the name of the class it is accompanying. A companion object is a singleton – there is only one instance of this object in the JVM. It has its own type and is not an instance of the accompanied class.
This object defines static functions or values that are closely related to the class it is accompanying. If you are familiar with Java, it replaces the keyword static: in Scala, all static members of a class are declared inside the companion object.
Some functions in the companion object have a special meaning. Functions named apply are constructors of the class. The name apply can be omitted when we call ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access