Generics
We've already seen generics in previous chapters, and in this section, we'll learn how they work, how they are implemented, and what the differences are from generics in Java.
Simply put, generics are types with parameters. Take a look at the List interface, for example; without generics, you could add objects of any type to it. But, since the list interface is generic, you have to specify a generic type for when you are creating an instance of it. You can create a list of strings, a list of integers, and so on. This then makes the list type-safe; you cannot add an integer to a list of strings.
The generic type is specified in angle brackets, so a list of strings type is declared like this:
List<String>
Creating an instance of a ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access