Introducing Generics for Classes and Functions in Scala

Lab Steps

Connecting to the Scala Web IDE
Working With Classes Generics
Working With Functions Generics

The hands-on lab is part of this learning path

Ready for the real environment experience?

Time Limit45m


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


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

About the Author
Learning paths5

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