Java's var keyword enables a lesser-known trick: assigning anonymous class instances to var-typed variables gives access to their ad-hoc fields and methods, which would otherwise be inaccessible. This works because the compiler infers the anonymous subtype rather than the declared supertype. The post demonstrates this with ad-hoc fields in stream pipelines (as a makeshift tuple) and ad-hoc methods on subclassed objects. Despite being technically clever, the author argues against using these patterns in production: they reduce readability by combining two non-trivial features, and they break down under refactoring since anonymous types can't appear in method signatures. Better alternatives include Map.Entry or FP library tuples for pairs, and direct subclassing or utility methods instead of ad-hoc methods.

6m read timeFrom nipafx.dev
Post cover image
Table of contents
▚ Ad-hoc Fields▚ Ad-hoc Methods▚ Reflection

Sort: