Unlocking Traits With var
This title could be clearer and more informative.Try out Clickbait Shieldfor free (5 uses left this month).
Java 10's var enables a trait-like pattern by combining lambda expressions, default methods, and intersection types. The technique involves creating a delegating interface (with a single abstract method returning the delegate) and trait interfaces with only default methods, then casting a lambda to their intersection and assigning it to a var variable. This allows ad-hoc composition of behaviors without creating explicit subclasses for every combination. However, the author strongly advises against using this in practice due to significant downsides: it relies on multiple non-trivial language features, intersection-typed variables can't easily cross method boundaries, and default methods cannot override Object methods like equals/hashCode, leading to subtle bugs in collections.
Table of contents
▚ What's A Trait?▚ Wait, I Thought These Were Intersection Types!?▚ Creating The Skeleton For Traits▚ Creating Traits▚ The Dark Side▚ ReflectionSort: