Chapter 5. Classes
This chapter begins a series of four chapters that cover the concept of domain modeling in Scala 3. Domain modeling is how you use a programming language to model the world around you, i.e., how you model concepts like people, cars, financial transactions, etc. Whether you’re writing code in a functional programming or object-oriented programming style, this means that you model the attributes and behaviors of these things.
To provide flexibility to model the world around you, Scala 3 offers the following language constructs:
-
Classes
-
Case classes
-
Traits
-
Enums
-
Objects and case objects
-
Abstract classes
-
Methods, which can be defined within all of those constructs
This is a lot of ground to cover, so to help manage that complexity, Recipe 5.1 shows how to use these constructs when programming in the FP and OOP styles. After that, classes and case classes are covered in this chapter, traits and enums are covered in Chapter 6, objects are covered in Chapter 7, and recipes for methods are provided in Chapter 8. Abstract classes aren’t used very often, so they’re touched upon in Recipe 5.1.
Classes and Case Classes
Although Scala and Java share many similarities, the syntax related to classes and constructors represents some of the biggest differences between the two languages. Whereas Java tends to be more verbose—but obvious—Scala is more concise, and the code you write ends up generating other code. For example, this one-line Scala class compiles ...
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.