Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·36

Generics

Exercises for Volume 3, chapter 36: the problem generics solve and the four implementation strategies (erasure, reification, monomorphisation, dictionary passing); generic classes and methods and type inference; bounds and associated types; variance from first principles, wildcards, PECS and declaration-site variance; erasure, reifiable types and heap pollution; and generics in Rust, Go, TypeScript and languages with higher-kinded types. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~14 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The exercises use the same four sets and the same locking as earlier chapters. They're written in Java 21, with comparisons in TypeScript 5, Go 1.24 and Rust 1.97. Every quoted output and compiler message below is real.

Five of the outputs catch experienced developers:

  • P2: <T extends Comparable<T>> T max(List<T>) would not compile for a List<LocalDate>. The Comparable<? super T> version worked.
  • P4: a generic pickTwo returning T[] threw ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; at a line with no visible cast.
  • P5: Box<String>, Box<Integer> and Box<List<String>> shared one static counter, and they are the same class at run time.
  • P7: TypeScript accepted const dishes: Dish[] = curries; dishes.push(new Dish()), and curries[1].spice was then undefined. A method-bivariant handler threw a TypeError at run time.
  • P8: Go rejected Twice(Paise(5)) with "Paise does not satisfy Exact (possibly missing ~ for int64 in Exact)".

The chapter's lab covered:

  • array covariance (ArrayStoreException)
  • heap pollution from an unchecked cast, which failed far from the bug
  • Collections.checkedList
  • erasure as seen by reflection, plus type tokens
  • the compile errors for name clashes and new T[n]
  • Go's generic sum, which ran about 5× faster than interface calls (9.4 ms vs 50 ms)

Coverage map.

Chapter component Exercises
the problem; four implementation strategies T1, P9
generic classes; generic methods; inference T2, P1, P3
bounds; recursive bounds; associated types T3, P2, P6
variance from first principles T4, P7
use-site variance (wildcards), PECS T5, P3
declaration-site variance T5, P7
type erasure; reifiable vs non-reifiable; heap pollution T6, P4, P5
monomorphisation (Rust, C++) T7, P9
Go's generics T7, P8
higher-kinded types; paradigm summary T8
generic API design T9, P6

Theory

T1. Why generics exist, and four ways to implement them

  1. Without generics, a List holds Object. Callers cast on every read, and a wrong element fails far from the line that inserted it (the lab's heap pollution shows the same failure mode). Show this with a pre-Java-5 List orders and a String that slipped in. What do generics move to compile time?
  2. Compare the four implementation strategies: - erasure (Java, Kotlin on the JVM, TypeScript) - reification (C#, Kotlin reified inline functions) - monomorphisation (C++, Rust) - dictionary passing / GC-shape stenciling (Haskell, Go)

For each, say what happens to the code size, the run-time type information, the performance with primitives, and the compile time. 3. Why did Java choose erasure in 2004, and what is it still paying for: boxing (ch33's lab, 18.7 ms vs 5.7 ms), no new T[], no instanceof List<String>, and overload clashes? What will Valhalla change?

T2. Generic classes, methods and inference

  1. Write Result<T, E> (a sealed interface with Ok and Err records), Page<T> (items, cursor, total) and a generic method static <T, K> Map<K, List<T>> groupBy(Collection<T> xs, Function<? super T, ? extends K> key). Explain the type parameter scopes (class-level vs method-level) and why static members can't use the class's type parameter (P5: one static counter shared by all Box<T>).
  2. Inference. P1 measured these cases: - List.of(1, 2.5) held an Integer and a Double, and its inferred type was List<Number & Comparable<…>>, an intersection type. - var x = new ArrayList<>() became ArrayList<Object> and accepted both "idli" and 42.

Explain target typing, the diamond operator, var, and when you must write explicit type witnesses (Collections.<Dish>emptyList()). 3. Explain raw types. P6's compile output gave "unchecked call to add(E) as a member of the raw type List". Why do raw types still exist, and how do you find and remove them?

T3. Bounds, recursive bounds and associated types

  1. Explain upper bounds (<T extends Number>), multiple bounds (<T extends Number & Comparable<T>>), and why <T extends Comparable<? super T>> is the correct bound for max. In P2, <T extends Comparable<T>> failed for a List<LocalDate>, because LocalDate implements Comparable<ChronoLocalDate>, not Comparable<LocalDate>.
  2. Explain recursive (F-bounded) generics: Enum<E extends Enum<E>>, Comparable<T>, and P1's self-typed builder (Builder<B extends Builder<B>> returning B from name()), which allowed new DishBuilder().name("Pesarattu").paise(7000).
  3. Explain associated types (Rust's type Id; in a trait, and Swift's associatedtype). P9's Repo trait with type Id = u32 returned Some("Pesarattu"). How do they differ from type parameters, and how do you emulate them in Java (Repository<T, ID>)?

T4. Variance from first principles

  1. Define covariance, contravariance and invariance using substitution. If a Curry is a Dish, is a List<Curry> a List<Dish>? Is a Consumer<Dish> a Consumer<Curry>? Is a Function<Dish, Curry> a Function<Curry, Dish>? Derive the rules: producers are covariant, consumers are contravariant, and anything that does both is invariant.
  2. Unsound covariance. Java arrays (the lab's ArrayStoreException) and TypeScript arrays (P7: curries[1].spice became undefined after pushing a Dish through a Dish[] alias) are covariant even though they're mutable. Explain why each language chose this, and how Java pays for it with a run-time check while TypeScript doesn't check at all.
  3. P7 also showed TypeScript method bivariance. A Handler<Curry> assigned to Handler<Dish> compiled and threw a TypeError at run time. A function-typed property (Fn<T> = (x: T) => void) was rejected under --strict with "Type 'Fn' is not assignable to type 'Fn'". Explain strictFunctionTypes and why methods are exempt.

T5. Wildcards, PECS and declaration-site variance

  1. Explain Java's use-site variance: - ? extends T: read Ts, can't add anything except null. P6's xs.add(1) on a List<? extends Number> failed with "int cannot be converted to CAP#1". - ? super T: add Ts, read only Object. P3's fill added Integers into both a List<Number> ([0, 1, 2]) and a List<Object> ([0, 1]). - ?: unknown type.

What is a capture (CAP#1), and when do you need a helper method to capture a wildcard? 2. State PECS ("producer extends, consumer super") and apply it to these signatures: - Collections.copy(dest, src) - addAll - Stream.map(Function<? super T, ? extends R>) - Comparator.comparing(Function<? super T, ? extends U>) - your own Pricing.applyAll(List<? extends PricingRule> rules, Consumer<? super Adjustment> sink)

When should a public API not use wildcards (return types)? 3. Compare declaration-site variance: Kotlin's out T and in T, Scala's +T and -T, C#'s out and in on interfaces, TypeScript 4.7's optional in and out annotations, and Rust's variance inferred for lifetimes. What does Java lose by having only use-site variance, and what does it gain?

T6. Erasure, reifiable types and heap pollution

  1. List what erasure removes and what survives. - Removed: type arguments of objects (the lab: new ArrayList<String>() is java.util.ArrayList at run time). P5 also showed that all Box<T> share one class and one static field. - Survives: generic signatures of declarations, available through reflection (the lab: the field's declared type List<Map<String, Integer>>) and through type tokens.

Define reifiable types (primitives, non-generic types, raw types, List<?>, arrays of reifiable types) and explain why only they can be used with instanceof and in array creation. 2. P4: pickTwo(T a, T b, T c) calling a @SafeVarargs-annotated toArray(T... xs) returned an Object[], and assigning the result to String[] threw ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;. Explain why. When is @SafeVarargs actually safe? 3. P6's compile errors: "Object cannot be safely cast to List" (instanceof List<String>), "generic array creation" (new T[n]), and "unchecked call to add(E) as a member of the raw type List". For each, give the workaround (List<?> with element checks, Class<T> or IntFunction<T[]> for arrays, removing raw types).

T7. Monomorphisation, Go's generics and the cost model

  1. Explain monomorphisation. P9 listed gen::show::<&str>, gen::show::<f64> and gen::show::<u8>: one compiled copy per type used, plus a single show_dyn for the &dyn Display version. What does each approach cost in binary size, compile time and run time? When do Rust programmers choose dyn Trait over generics?
  2. Go's generics (1.18+): - type sets in constraints (~int | ~int64 | ~float64) - the tilde for underlying types: P8's Sum[Paise] worked with ~int64, but Exact without ~ rejected Paise ("possibly missing ~ for int64 in Exact") - GC-shape stenciling with dictionaries - no generic methods on types, and no specialisation

The lab measured 9.4 ms for generics, 50 ms for interfaces and 25.7 ms for any. Explain the results. 3. Write the cost model a senior engineer should carry: erasure plus boxing (Java), reified with value-type specialisation (C#), monomorphised (Rust/C++), shape-stenciled (Go), erased to dynamic JavaScript (TypeScript, which has zero run-time effect). For each, what should you never do in a hot loop?

T8. Higher-kinded types and the paradigm summary

  1. Explain higher-kinded types: abstracting over a type constructor (F<_>) rather than a type, as in Haskell's Functor f or Scala's F[_]. Show why Java can't write interface Functor<F> { <A, B> F<B> map(F<A> fa, Function<A, B> f); }, and the workarounds (Arrow-style "Kind" encodings, or duplicating map on Optional, Stream, CompletableFuture).
  2. Do backend engineers need higher-kinded types? Discuss what they buy in Scala and Haskell codebases (generic effect types, F[_]: Monad tagless final), and the cost in team comprehension.
  3. Summarise the paradigms in a table: Java, C#, Kotlin, TypeScript, Go, Rust, C++, Haskell. Cover the mechanism, variance, run-time types, primitives, and whether the language has higher-kinded types.

T9. Designing generic APIs

  1. When should a backend API be generic? Contrast a generic Repository<T, ID> (Spring Data), Result<T, E>, Page<T>, EventHandler<E extends DomainEvent> and a Cache<K, V> with over-generic designs: Service<T, R, C, E> that nobody can read, and type parameters used only once.
  2. Rules for readable generic signatures: name type parameters meaningfully when there are several (<K, V>, <E extends DomainEvent>), apply PECS on parameters and no wildcards on returns, avoid more than two type parameters in public APIs, and prefer concrete types where only one is used.
  3. How do generics interact with Jackson and Spring? Cover deserialising Page<Dish> (type tokens, JavaType), Spring injecting EventHandler<OrderPlaced> beans by generic type (ResolvableType), and why erasure makes some of this fragile.

Programming exercises

P1. Inference, the diamond and self types

Show these four cases:

  • List.of(1, 2.5) and its element classes, plus sum(Collection<? extends Number>)
  • var x = new ArrayList<>() accepting mixed types
  • a self-typed builder hierarchy
  • a function used through wildcard types

Then fix the var problem, and write a base Builder<B extends Builder<B>> with two subclasses (DishBuilder, ComboBuilder) whose chained calls keep their own types.

P2. Bounds that work with real JDK types

Write max with <T extends Comparable<T>> and with <T extends Comparable<? super T>>, then call both with a List<LocalDate>. Capture the compiler error. Then write the following:

  • a clamp(T value, T min, T max) with the correct bound
  • a sortedCopy(Collection<? extends T>, Comparator<? super T>)
  • a minBy(Collection<T>, Function<? super T, ? extends U>) where U is comparable

P3. PECS in practice

Write these three functions:

  • fill(List<? super Integer>, n), showing it works with a List<Number> and a List<Object>
  • copyMatching(List<? extends T> src, List<? super T> dst, Predicate<? super T> p)
  • Pricing.applyAll(List<? extends PricingRule>, Consumer<? super Adjustment>)

Then show the compile error from adding to a List<? extends Number>, and write a capture helper for swap(List<?>, i, j).

P4. Heap pollution and @SafeVarargs

Reproduce pickTwo's ClassCastException and the lab's unchecked cast that fails at the read. Then fix both:

  • return List<T> from pickTwo
  • put @SafeVarargs only on methods that don't let the array escape
  • replace the unchecked cast with a checked one using Class<T>

Find every @SuppressWarnings("unchecked") in a sample codebase and classify each one as justified or not.

P5. Erasure in practice

Show these four things:

  • one static counter shared by all Box<T>, and that Box<String>.class == Box<Integer>.class
  • the lab's reflection of declared generic types
  • a type token (TypeReference-style) recovering Map<String, List<Integer>>
  • Jackson deserialising Page<Dish> without a type token (elements become LinkedHashMap) and with one

P6. Compile errors you'll meet

Collect these compiler messages and write the idiomatic fix for each:

  • instanceof List<String>
  • new T[n]
  • adding to ? extends
  • raw type add
  • overload with the same erasure
  • a static field of type T

Then write toArray(Collection<T>, IntFunction<T[]>).

P7. Variance holes in TypeScript

Reproduce the two holes in TypeScript under --strict:

  • covariant arrays (curries[1].spice undefined)
  • method bivariance (a TypeError at run time)

Then show strictFunctionTypes rejecting the function-property version. Fix the designs with readonly arrays, callback properties instead of methods, and explicit in/out variance annotations. Compare with Java's invariant generics (a compile error) and arrays (a run-time ArrayStoreException).

P8. Go generics: constraints, tilde and limits

Write these in Go:

  • Sum[T Number] with ~int | ~int64 | ~float64, used with type Paise int64
  • Map[T, U any]
  • a generic Set[T comparable]

Show the error when the constraint lacks ~. Then try to write a generic method (func (s Set[T]) Map[U any](...)), capture the error, and restructure it as a function.

P9. Monomorphisation and dynamic dispatch in Rust

Write show<T: Display> and show_dyn(&dyn Display), use the first with three types, and list the generated symbols in a debug build. Then do the following:

  • measure binary size with 1 instantiation against 20 instantiations of a larger generic function
  • write a repository trait with an associated Id type
  • explain when you'd box trait objects

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–36)

C1. A typed Result and validation library for TiffinBox

Build a small library with these parts:

  • Result<T, E> (sealed, with map, flatMap, mapError, getOrElse and fold)
  • Validation<T>, which accumulates errors instead of stopping at the first
  • Page<T> with cursor encoding
  • typed ids, Id<T> as record Id<T>(UUID value), so Id<Order> and Id<Dish> can't be confused

Use the library in the cart and order domain from ch33 and ch34, with PECS-correct signatures, and test it with jqwik.

Combines: Volume 1's error handling, Volume 2's typed API clients (ch19) and TypeScript discriminated unions (ch16), ch33's error models, ch34's sealed types, and this chapter.

C2. A generic, type-safe event bus

Implement an in-process EventBus with these methods:

  • <E extends DomainEvent> void subscribe(Class<E> type, EventHandler<? super E> h)
  • publish(DomainEvent e), which dispatches to handlers registered for the event's class and its supertypes, in a deterministic order

Handle these cases: handler exceptions (isolate them, and collect the failures); registration through Spring-style generic type resolution from handler classes; and a contract that lambda handlers must pass Class<E> explicitly because of erasure (T9). Test with OrderPlaced, OrderAccepted and a supertype handler for all OrderEvents.

Combines: Volume 1's observer pattern, Volume 2's frontend event patterns (ch25), ch34's sealed events, ch35's ordered maps, and this chapter.

C3. Port a generic utility across four languages

Port groupBy, Page<T> and Result<T, E> to TypeScript, Go and Rust. Then compare the results: how each expresses the constraint "keys must be hashable/comparable", whether Result can be exhaustively matched, where variance appears, and the run-time cost. Include each language's compiler error for one deliberate misuse.

Combines: Volume 2's TypeScript generics (ch16), ch33's language comparison, and this chapter.

What the chapter leaves out

Generic type inference failures and how to read them

Real-world generic errors are long ("inference variable T has incompatible bounds: equality constraints: … lower bounds: …"). Read them from the bottom up: find the expected type, the actual type, and the call where inference got its constraints. Common fixes: annotate lambda parameters, split a long chain into variables with explicit types, or add a type witness. IntelliJ's "show inferred types" helps.

Type-safe heterogeneous containers

A Map<Class<?>, Object> with <T> T get(Class<T> key) { return key.cast(map.get(key)); } (Bloch's "typesafe heterogeneous container") stores values of different types safely, keyed by type. It's used for request attributes, plugin registries and configuration. Use TypeReference-style keys for generic types. Spring's ResolvableType and Guice's TypeLiteral are industrial versions.

Generics and lambdas: functional interface variance

Function<? super T, ? extends R> appears everywhere in streams (ch37). Lambda parameter types are inferred from these wildcards, which is why Comparator.comparing(Dish::paise).reversed() sometimes fails to infer: reversed() breaks the target typing. Write Comparator.comparing(Dish::paise, Comparator.reverseOrder()), or give the lambda an explicit parameter type. Chapter 37 covers functional composition.

Annotation-based nullness and generics

List<@Nullable String> versus @Nullable List<String>: with JSpecify, type-use annotations apply to type arguments as well as to types, so nullness tooling (NullAway) can check generic code ("may this list contain nulls?"). Kotlin interop uses the same annotations to decide between List<String?> and List<String>. Annotate generic APIs carefully. Chapter 33 covered null safety in general.

Project Valhalla and specialised generics

Value classes (JEP 401, in preview in early-access builds) remove identity, so the JVM can flatten them. Later phases aim for generics over primitives and values without boxing (List<int>-like performance). This would change the cost model in T7 for Java. Follow the JEPs, but don't design around unreleased features.

Senior exercises

S1. Write the team's generics guidelines

Write a one-page set of generics guidelines covering:

  • when to introduce a type parameter
  • naming
  • PECS on parameters, with no wildcards in returns
  • bounds such as Comparable<? super T>
  • suppressions and their comments
  • arrays versus lists
  • var with the diamond
  • type tokens for frameworks
  • the build flags that enforce all of this

Tie each rule to an output from this chapter.

S2. Review a generic framework someone wrote

A teammate built GenericCrudController<E extends BaseEntity<ID>, ID extends Serializable, D extends BaseDto, M extends Mapper<E, D>, S extends BaseService<E, ID>>. Every endpoint extends it, and all the rules live in BaseService hooks (beforeSave, afterSave). Endpoints that need special behaviour override hooks and cast. Write the review and propose a migration.

S3. Decide whether to adopt a functional library (Vavr) for Result and collections

A team proposes adopting Vavr for Either, Try, Option, persistent collections and pattern matching. Weigh it against Java 21's sealed types and records, the JDK's immutable collections, and a small in-house Result. Consider learning curve, interop with Jackson, JPA and Spring, IDE support and long-term maintenance. Write the decision.

S4. Teach variance with three outputs

Prepare a 15-minute session using three outputs:

  • the lab's ArrayStoreException (Java arrays: covariant, checked)
  • P7's curries[1].spice = undefined (TypeScript arrays: covariant, unchecked)
  • P3's fill into List<Number> and List<Object> (Java wildcards: safe and flexible)

End with PECS and one exercise for the audience.

S5. Plan a language-version and generics clean-up for a legacy codebase

A 300,000-line codebase has 2,800 raw-type warnings, 600 @SuppressWarnings("unchecked") annotations, arrays of generics in public APIs, a homemade Pair<A, B> used for everything, and Object parameters in services. Plan a 6-month clean-up that ships continuously, with how you'll measure progress and avoid regressions.