Introducing Generics for Classes and Functions in Scala
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:
- Understanding Basic Scala Elements for Functional Programming
- Starting using Recursion with Scala
- Creating and Handling Classes and Hierarchies in Scala
Updates
April 20th, 2023 - Updated theia to enable autosave