hands-on lab

Introducing Generics for Classes and Functions in Scala

Difficulty: Intermediate
Duration: Up to 45 minutes
Students: 97
Rating: 5/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

When you build software leveraging the OOP or the functional paradigms, you should fall into the situation where you want to let a class or a function assume different possible forms: you want it to be polymorph. Suppose you have a class that models binary trees (each tree has an item, and two children that are trees) and want to be able to instantiate trees that contain Int, Float, String, and other possible types. Without any form of polymorphism, you should create a class for each type you want to support.

To accomplish this problem, Scala offers you the possibility to leverage generics to set one or more type parameters for both classes and functions. The type parameters can be used within the class or function, and they are instantiated when you use the entity. That way you can build only one function, or class, and be able to let it assume different forms depending on the instantiated type parameters.

When you need to use generics, you have to use the [] brackets, and inserting into them the list of type parameters.

In this lab, you will leverage generics to create polymorph classes and functions in Scala.

Learning Objectives

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

  • Understand how generics work
  • Create classes and functions with type parameters

Intended Audience

This lab is intended for:

  • Software engineers who need to create polymorph classes and functions in Scala
  • Developers who want to learn how to implement classes and functions efficiently

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
Working With Classes Generics
Working With Functions Generics