hands-on lab

Creating and Handling Classes and Hierarchies in Scala

Difficulty: Intermediate
Duration: Up to 1 hour
Students: 115
Rating: 3.4/5
Get guided in a real environmentPractice with a step-by-step scenario in a real, provisioned environment.
Learn and validateUse validations to check your solutions every step of the way.
See resultsTrack your knowledge and monitor your progress.

Description

If you are building software and need to model the entities that will be part of the program you are developing, you should consider using classes. Classes are concepts that refer to the OOP (Object Oriented Programming) but can be also used and integrated with functional programming.

A class represents an entity and models a set of fields (mostly referenced as the state), and behavior (which is a set of methods). After having defined a class, to create and manage the entities it represents, you need to instantiate it by creating an object of that class. Each defined class also creates a type, and the objects created will be of that specific type.

Different classes with common parts can be put in a hierarchy. If you build a hierarchy, you will have top-classes and sub-classes. A top-class represents a generic class, a sub-class represents a more specialized class (a subclass inherits from a top-class).

In Scala, you can define classes and hierarchies. Scala only supports single inheritance, which means that you can only inherit from a single top-class. Scala gives you the possibility to create abstract classes: classes that could have abstract methods (methods with no implementation). Abstract classes can't be instantiated, so you can't create objects from them. If you want to cheat the single-inheritance model, you can consider the Traits. A trait is a class that is like an abstract class, but you can extend more than one trait from a class.

In this lab, you will define and use classes, abstract classes, and traits, and you will put them in a hierarchy.

Learning Objectives

Upon completion of this beginner level lab, you will be able to:

  • Create classes, abstract classes, and traits
  • Understand when and where use the different types of classes

Intended Audience

This lab is intended for:

  • Software engineers who want to leverage the OOP possibilities offered by Scala
  • Developers who want to use the functional paradigm and integrate it with the OOP one

Prerequisites

To get the most out of this lab, you should have basic knowledge of Scala. To achieve this, we suggest taking the following labs:

Updates

April 20th, 2023 - Updated theia to enable autosave

Covered topics

Lab steps

Connecting to the Scala Web IDE
Introducing Abstract Classes and Traits in Scala
Introducing Concrete Classes in Scala