Generics

Generics are another way of parameterizing classes. They are useful when we write a functionality whose application is the same throughout various types, and we can simply defer choosing a concrete type until later. One example every developer should be familiar with is collection classes. List, for example, can store any type of data, and we can have lists of integers, doubles, strings, custom classes, and so on. Still, the list implementation is always the same.

We can also parameterize methods. For example, if we want to implement addition, it will not change between different numerical data types. Hence, we can use generics and just write our method once instead of overloading and trying to accommodate every single type in the ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.