0

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 ?

durron597
  • 31,968
  • 17
  • 99
  • 158
David Moles
  • 48,006
  • 27
  • 136
  • 235
  • Hi @DanielDietrich—sorry, there were a lot of typos in there. Yes, it should have been Option and Try – David Moles Oct 30 '17 at 19:57
  • FWIW, the eventual target is an [io.reactivex.Maybe](http://reactivex.io/RxJava/javadoc/io/reactivex/Maybe.html), which (as I understand it so far) is sort of an asynchronous Try/Option combination: it can provide one value, no values, or an error. – David Moles Oct 30 '17 at 20:00
  • I think the code smell is that the implementation of B depends on the implementation of A. Why would that be? – durron597 Nov 06 '17 at 19:05
  • @durron597 This code is converting between two different APIs with parallel data structures. There are a number of possible approaches other than this one, but the general question of "how do I convert an unmatched case to a Try failure" is relevant in other circumstances. – David Moles Nov 07 '17 at 19:39
  • @DavidMoles is that the part that you thought was stinky? The part I found stinky was the matching in the first place. If you assume that the first three cases of your `Match` are basically correct, then I think it follows that `$(), Failure(...` is also correct. – durron597 Nov 07 '17 at 20:33

0 Answers0