Advertisement
Advanced Java, Generics

How would you implement a generic pair/tuple utility method that returns different concrete types depending on the number of elements, and how does target-type inference help the compiler choose the correct generic instantiation from context alone?

Short answer

A well-designed generic factory method (like a static of() method) relies on the compiler's target-type inference to determine the appropriate type arguments purely from the context where the result is USED (the declared variable type, a method parameter type, or a return type)…

Save Java mock interview
Advertisement
AModel answer
A well-designed generic factory method (like a static of() method) relies on the compiler's target-type inference to determine the appropriate type arguments purely from the context where the result is USED (the declared variable type, a method parameter type, or a return type), without requiring explicit type arguments at the call site -- this became notably more capable in later Java versions (target typing improvements), letting increasingly sophisticated inference scenarios (like inferring generic types through nested generic method calls, or from a lambda's inferred parameter types) resolve correctly without any explicit type witnesses, significantly reducing the verbosity that earlier, more limited inference would have required.
public class Pair<A, B> {
    private final A first;
    private final B second;
    private Pair(A first, B second) { this.first = first; this.second = second; }
    public static <A, B> Pair<A, B> of(A first, B second) { return new Pair<>(first, second); }
}

// Target-type inference determines A=String, B=Integer purely from the assignment context
Pair<String, Integer> pair = Pair.of("age", 30);
Real-world example
A utility library's generic Pair.of(a, b) factory method relies entirely on target-type inference to determine its type arguments from how the result is used, letting calling code write concise, unadorned factory calls without ever needing to spell out explicit generic type arguments, even in fairly complex nested-generic scenarios.
Likely follow-ups
  • What specific Java version introduced meaningfully improved target-type inference, and what scenarios did it newly support?
  • How does this inference interact with method overloading when multiple overloads could each plausibly match?
Related topics