Generics, SubTypes and SuperTypes

Scala Comments

In this blog post, you’ll learn about -

  1. How to define a Generic class and a Generic function.
  2. How to restrict the type of the parameters being passed to a function.


As in Java, classes and traits can have type parameters. Consider the example below,

The above code defines a class that has 2 parameters - first (of type T) and second (of type S). This is very useful as when you want to build a Pair object, now the 2 parameters could be of any type.

Generic Functions

What’s happening above?

  1. We’ve defined a generic function - a function of type T.
  2. It takes in a parameter a - an Array of type T.
  3. It then returns the middle element. Hence the function return type is T.


Consider the pair class in the example above but where both the elements are of the same type -

The function throws an error as you do not know if the type T has a compareTo method. In order to impose this restriction, you need T to be a sub-Type of Comparable[T]. What this means is that, Comparable must be a parent of T.

In a similar way, you can also define supertypes using the ‘>:’ operator. More specifically, you could combine both the subType and superType this way -

Kaushik Rangadurai

Code. Learn. Explore

Share this post