I have written a simple class hierarchy to represent terms in Scala. Terms are recursive data types, e.g., a Sum and a Multiplication consist of the left-hand-side (lhs), which is a Term, and the right-hand-side (rhs), which is also a Term.Scala's pattern matching makes it easy to check if a Term has a given structure.  For instance, here's a method that returns t3 from the Term if it is structured as t1 * (t2 + t3):def fetchT3(t: Term): Option[Term] = Some(t).collect {  case Multiplication(t1, Sum(t2, t3)) => t3}Now I want to write the same in Java, but the lack of pattern matching makes it difficult. Usage of the instanceof operator if frowned upon, but I haven't found a real alternative. Here's what I have come up with so far:public static <T> Optional<T> maybeAs(final Object obj, final Class<T> clazz) {    try {        return Optional.of(clazz.cast(obj));    } catch (ClassCastException exc) {        return Optional.empty();    }}The fetchT3 method from above can then be written as:public Optional<Term> fetchT3(final Term t) {    return maybeAs(t, Multiplication.class).flatMap(mult ->            maybeAs(mult.rhs, Sum.class).map(sum ->                    sum.rhs            )    );}What I dislike about this approach is that first, it's using Exceptions for situations which are not truly exceptional, and second, it will become hard to read when terms are deeply nested. Using exceptions can be avoided by writing one method for each class (maybeAsSum, maybeAsMultiplication, ) and then using instanceof, which would one the other hand introduce code redundancy. Either way, casting classes is usually seen as a symptom of poor design in Java, but I don't know a way around it.So my question is, would you consider this as an example of acceptable usage of class casting, or do you see a better method to check the term structure?
Avoiding instanceof for recursive data types
java;scala;type casting