Cover by Alex Payne, Dean Wampler

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Companion Objects

Recall that fields and methods defined in objects serve the role that class “static” fields and methods serve in languages like Java. When object-based fields and methods are closely associated with a particular class, they are normally defined in a companion object.

We mentioned companion objects briefly in Chapter 1, and we discussed the Pair example from the Scala library in Chapter 2. Let’s fill in the remaining details now.

First, recall that if a class (or a type referring to a class) and an object are declared in the same file, in the same package, and with the same name, they are called a companion class (or companion type) and a companion object, respectively.

There is no namespace collision when the name is reused in this way, because Scala stores the class name in the type namespace, while it stores the object name in the term namespace (see [ScalaSpec2009]).

The two most interesting methods frequently defined in a companion object are apply and unapply.

Apply

Scala provides some syntactic sugar in the form of the apply method. When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method for that instance. This is true for an object with a defined apply method (such as a companion object), as well as an instance of a class that defines an apply method.

In the case of an object, apply is conventionally used as a factory method, returning a new instance. This is what Pair.apply does in the ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required