Hacker News new | ask | show | jobs
by rdnetto 3341 days ago
Would be really great to see this make it's way into the language. Here are some ways I've found to work around its absence: * adding a match() function to a common base type. So if it could have subtypes Foo(x), Bar(y, z), then the signature would look like:

  <T> T match(Function<X, T> foo, BiFunction<Y, Z, T> bar);
* in the cases where I don't have control over the common base type, I've written a builder pattern that constructs a sequence of predicate-function pairs and applies them appropriately. This looks like so:

    new PatternMatchingHelper()
    .append(Foo.class, foo -> doSomething(foo.x))
    .append(Bar.class, bar -> doSomethingElse(bar.y, bar.z))
    .otherwise(x -> fallbackValue())
    .apply(objectOfUnknownType);
The main disadvantage here is that it doesn't work well with generics, because the class objects have raw types.

You could probably extend the second approach to get something close to the arbitrary predicates that pattern matching would provide, but the syntax wouldn't be nearly a clean as having it in the language.

1 comments

Just use another language if you want pattern matching so badly. Twisting Java to look like Scala doesn't do the language justice.
You act as if what op described must be the entirety of their code base. What if pattern matching is just a small part of a larger problem better solved with Java?
It's not so easy to just choose another language; there might be hundreds of thousands of lines of Java already written. In that case it's better make the best of a bad situation by doing something like this, than not even trying.