Tags

Generics

Generics

0 lessons
3 code snippets
1 community item

generics

Code Snippets

3 snippets
Code Snippet

Bounded Generics with extends

Bounded type parameters and wildcards (`<T extends Number>`, `<? extends Number>`, `<? super Integer>`) are how Java balances type safety with API flexibility. This snippet shows an upper-bounded type parameter for arithmetic, the producer-extends-consumer-super (PECS) rule with wildcards, and a comparator-driven generic max function. Get these right and your collection APIs will accept everything the caller reasonably wants to pass.

Java
java-generics
generics
type-system

745

9

Medium
Code Snippet
Premium

Template Constraints with C++20 Concepts (and SFINAE Fallback)

C++20 concepts (`requires` clauses) replace decades of SFINAE incantations with readable predicate-style template constraints. The runnable accordions in this entry use the C++17 `std::enable_if_t` SFINAE form because the test compiler is GCC 9.2 (which lacks concepts), and the C++20 equivalent is shown in inline comments. Reach for concepts on any compiler that supports them; reach for SFINAE only when constrained by toolchain age.

C++
cpp-templates
cpp-metaprogramming
type-system
generics

870

16

Hard
Code Snippet
Premium

Go Generics with Type Constraints

Go 1.18 added generics; Go 1.21 polished them with the new `cmp` and `slices` packages. This snippet shows a generic `Map`, a numeric constraint via `~int | ~float64`, and a `comparable`-bounded set type. The runnable code targets Go 1.18 syntax (no `cmp.Ordered`, no `slices.Sort`) so it compiles on as many Go versions as possible; the 1.21+ shortcuts are referenced in comments. Note: the project's test runner uses Go 1.13.5 which predates generics, so test execution is expected to FAIL there but the code is valid Go 1.18+.

Go
generics
type-system
go-modules

236

3

Hard