Chapter 9. Objects, Case Classes, and Traits

In the previous chapter we covered classes, a core component of object-oriented Scala. As you’ll recall, classes are defined once but can be instantiated an unlimited number of times. In this chapter we will discover new components that may be used to complement and embellish classes, or replace some classes entirely, depending on your object-oriented design preferences. Many developers choose the latter, using them in place of “regular” classes when they can. Therefore I highly recommend taking the time to learn about each component, not only because you also may end up preferring them over classes but also because they all have something new to offer most developers.

The three new components—objects, case classes, and traits—are sufficiently discrete that there is little point in writing a common introduction for them. Therefore, in this chapter we will have separate introductions for each component, starting with the section on objects.

Objects

An object is a type of class that can have no more than one instance, known in object-oriented design as a singleton. Instead of creating an instance with a new keyword, just access the object directly by name. An object gets automatically instantiated the first time it is accessed in a running JVM, which also means that until it is accessed the first time it won’t get instantiated.

Java and other languages have the ability to designate certain fields and methods of a class as being ...

Get Learning Scala 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.