3 ms·
Switch expressions prepare the way for pattern matching (https://openjdk.java.net/jeps/305 https://openjdk.java.net/jeps/305), instead of `instanceof` checks an
by hyperpallium 8y ago
Switch expressions prepare the way for pattern matching (https://openjdk.java.net/jeps/305 https://openjdk.java.net/jeps/305), instead of `instanceof` checks and casts.
But (in my naive opinion) double dispatch seems a more elegant and java-ry solution, i.e. polymorphism on argument classes, so different methods are invoked for different object runtime classes (instead of using the compiletime type of the variable).
The switching could be optimised, as ordinary polymorphism is in the JVM.
Sure, you'd wreck legacy code if you just introduced it, but there's surely a backcompatible way to do it that isn't too awkward.
BONUS: goodbye visitor pattern!
- aardvark179 8y agoThat kind of multiple dispatch would be far more disruptive at several levels, and still wouldn’t really get you where you want to go without a lot more compiler and JIT magic. Sure, you could match on types, but you wouldn’t be able to extend that to destructuring patterns, or regsxps as patterns on strings, or so many other ways patterns may be extended in future releases.
- hyperpallium 8y agoMy comment's a little out of place. I'm not against pattern matching, but for double dispatch; we can have both. Their initial motivating examples was bare instanceof, but I now see they extend it. How would destructuring fit this model ?!
- aardvark179 8y agoBrian Goetz has writes quite a bit about ongoing projects. The latest article he has done about pattern matching is I think http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.h.... There is a load of stuff in there about destructuring patterns from about half way down.
- hyperpallium 8y agoThanks, a methodical article! Not keen on special support required for destructuring. Nice that they discuss Visitor pattern (and the switch example for such cases looks nice). They don't dicuss double dispatch - but not relevant to them.
- keyle 8y agoI'm learning Swift on the side, I was pleasantly surprised by this.