Chapter 7. Objects

Continuing the domain modeling chapters, the word object has a dual meaning in Scala. As with Java, you use the name to refer to an instance of a class, but in Scala object is much more well known as a keyword. This chapter demonstrates both meanings of the word.

The first two recipes look at an object as an instance of a class. They show how to cast objects from one type to another and demonstrate the Scala equivalent of Java’s .class approach.

The remaining recipes demonstrate how the object keyword is used for other purposes. In the most basic use, Recipe 7.3 shows how to use it to create singletons. Recipe 7.4 demonstrates how to use companion objects as a way to add static members to a class, and then Recipe 7.5 shows how to use apply methods in companion objects as an alternative way to construct class instances.

After those recipes, Recipe 7.6 shows how to create a static factory using an object, and Recipe 7.7 demonstrates how to combine one or more traits into an object in a process that’s technically known as reification. Finally, pattern matching is a very important Scala topic, and Recipe 7.8 demonstrates how to write an unapply method in a companion object so your classes can be used in match expressions.1

7.1 Casting Objects

Problem

You need to cast an instance of a class from one type to another, such as when creating objects dynamically.

Solution

In the following example I’ll work with the Sphinx-4 speech recognition library, which works ...

Get Scala Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.