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 (FP) or object-oriented programming (OOP) style, this means that you model the attributes and behaviors of these things.

To provide flexibility to model the world around you, Scala 3 provides 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, “Choosing from Domain Modeling Options” 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 represent 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 ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.