Generics, SubTypes and SuperTypes
In this blog post, you’ll learn about -
- How to define a Generic class and a Generic function.
- 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.
What’s happening above?
- We’ve defined a generic function - a function of type T.
- It takes in a parameter a - an Array of type T.
- 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 -
Code. Learn. Explore