Idiomatic Pattern Matching Equivalent in Java

designjavapattern matchingvisitor-pattern

I'm building a simulator which parses some events from STDIN and "runs" them. My background is mostly functional programming these days, so it seemed natural to do something like this:

data Event = Thing1 String Int | Thing2 Int | Thing3 String String Int
Parse :: String -> [Event]
Simulate :: [Event] -> [Result]

where simulate would be

case event
  of Thing1 a b => compute for thing one
   | Thing2 a => compute for thing two

etc. What is the idiomatic way to do this sort of thing in Java? Googling has pointed me in the direction of nested classes and the visitor pattern, but that seems rather heavyweight in my attempt. Type erasure seems to be fighting me, hard. Could you show me an outline of what that would look like done correctly?

Best Answer

The author of 'Functional Programming in Scala' gives a nice illustration of the best that can be achieved in Java in a type safe manner:

http://blog.higher-order.com/blog/2009/08/21/structural-pattern-matching-in-java/

Essentially, it uses a Church-encoding of the cases to ensure that the compiler will complain if any are missing.

The details are not readily summarized and indeed are so well covered in the article that there's no point in reproducing them here (that's what hyperlinks are for right?).

Related Topic