Introducing Generics for Classes and Functions in Scala

Lab Steps

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

The hands-on lab is part of this learning path

Ready for the real environment experience?

DifficultyIntermediate
Time Limit45m
Students20
Ratings
5/5
starstarstarstarstar

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:

About the Author
Students18362
Labs94
Courses2
Learning paths7

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