hands-on lab

Introducing Generics for Classes and Functions in Scala

Intermediate
45m
92
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.
Lab 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

About the author
Students
40,024
Labs
106
Courses
2
Learning paths
10

Stefano studies Computer Science and is passionate about technology. He loves working with Cloud services and learning all the best practices for them. Google Cloud Platform and Amazon Web Services are the cloud providers he prefers. He is a Google Cloud Certified Associate Cloud Engineer. Node.js is the programming language he always uses to code. When he's not involved in studying or working, Stefano loves riding his motorbike and exploring new places.

Covered topics
Lab steps
Connecting to the Scala Web IDE
Working With Classes Generics
Working With Functions Generics