Introduction

Although Scala and Java share many similarities, the declaration of classes, class constructors, and the control of field visibility are some of the biggest differences between the two languages. Whereas Java tends to be more verbose (yet obvious), Scala is more concise, and the code you write ends up generating other code.

Recipes in this chapter will help you get through the initial learning curve related to Scala classes and fields by demonstrating how class constructors work, and the code the Scala compiler generates on your behalf when you declare constructor parameters and class fields using the val, var, and private keywords.

Because the Scala compiler generates accessors and mutators based on your field declarations, you may wonder how to override those methods, and this chapter provides recipes showing how to override that generated code.

Additionally, because Scala automatically sets the field type based on the value you assign, you may wonder, “What happens when a field has no initial value?” For instance, you may want to create an uninitialized field as an instance of an Address class. As you think about this you start typing the following code, and then wonder how to complete it:

var address = ?     // how to create an uninitialized Address?

This chapter shows the solution to that problem, demonstrates how declaring a class as a case class results in more than 20 additional methods being generated, shows how to write equals methods that work with class inheritance, and much more.

Note

In Java, it seems correct to refer to accessor and mutator methods as “getter” and “setter” methods, primarily because of the JavaBeans standard. In this chapter, I use the terms interchangeably, but to be clear, Scala does not follow the JavaBeans naming convention for accessor and mutator methods.

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