44
Tricks with ‘var’ and anonymous classes (that you should never use at work)

Tricks with ‘var’ and anonymous classes (that you should never use at work)

6 years ago
ian $qJbmSRWi1z

https://blog.codefx.org/java/tricks-var-anonymous-classes/

Using var to infer types of local variables is a great tool for writing readable code. More than that, it makes working with intersection types much more pleasant. It has a dark underbelly, though, and while experimenting with it I found a few var-tricks related to anonymous classes (ad-hoc fields and ad-hoc methods) that were fun to explore but I think are ultimately not fit for duty.

These tricks hinge on the fact that compiler and JVM know a richer type system than can be expressed with Java’s syntax. With var, though, a type does not need to be written out and can instead be determined by the more powerful compiler. This is particularly helpful when working with anonymous classes, which can not be expressed in source code.