Generics and templates
medium 45 minWrite a class or a function once, leave a blank for the type, and fill the blank at each use.
Watch lesson4:52
Where it shows up
The same pattern appears across everyday software.
Java collections
`List<E>` and `Map<K, V>`. `Collections.checkedList` adds a test at run time, to find code that pollutes a list.
Guice TypeLiteral
Its documentation shows `new TypeLiteral<List<String>>() {}`, an anonymous class that keeps the full generic type.
Jackson TypeReference
An abstract class whose purpose is to obtain full generics type information by subclassing.
Gson TypeToken
The user guide reads a `Collection<Integer>` from JSON with a TypeToken.
Spring Data CrudRepository
`CrudRepository<T, ID>`: one interface for saving and finding any entity with any kind of id.
Rust
The Rust book explains monomorphisation: generic code is turned into specific code, so there is no cost at run time.
C# and .NET
Microsoft's documentation says that the runtime makes a specialised type for value type arguments, and reuses code for reference types.
Go
Type parameters since 1.18. The FAQ says that the compiler may compile instantiations separately or share them.
C++20 concepts
Named requirements on template arguments, checked at compile time, described on cppreference.
Python typing
PEP 484 made type hints standard, with TypeVar and Generic. PEP 695 gave them short syntax in 3.12.