Say I have two interfaces, A and B. A has three known implementations, A1, A2, and A3; B has three corresponding concrete wrapper classes, B1, B2, and B3, such that the constructor of B1 takes an A1, B2 takes an A2, and so on.
I have a method that returns an Option<A>, and I want to convert it to a Try<Option<B>>, where if the A is one of the known implementations (or None) it gets wrapped with the corresponding B implementation as a Success<B>, and otherwise it's a Failure. What I currently have is something like:
Option<A> myA = getA();
Try<Option<B>> wrapped = Match(myA).of(
Case($Some($(instanceof(A1.class))), a -> Success(Some(B1(a)))),
Case($Some($(instanceof(A2.class))), a -> Success(Some(B2(a)))),
Case($Some($(instanceof(A3.class))), a -> Success(Some(B3(a)))),
Case($None(), a -> Success(None())),
Case($(), Failure(new IllegalArgumentException("Unknown A type: " + myA)))
);
This seems unnecessarily horrible. Is there some way I can flatmap this ?