In my Java application I created methods that return Either<String, T>
objects.
This is because in some places I invoke these methods as the parameter of (3rd party) methods that expect a String parameter as input. While in other places I invoke these methods as the parameter of (3rd party) methods that expect some other parameter type (T) as input.
So depending on the place where I invoke the methods that I created, the code looks like:
their.thirdPartyExpectsString(my.calculateEither().getLeft());
their.thirdPartyExpectsString(my.calculateEither() + "");
or
their.thirdPartyExpectsDouble(my.calculateEither().getRight());
(I defined Either.toString()
as Either.getLeft()
).
Pay attention, I cannot change the 3rd party code (anyway not without bytecode manipulation), and I would like to keep my design in which I return Either
from my methods.
Is there a way to simplify my code and make it look like
their.thirdPartyExpectsString(my.calculateEither());
their.thirdPartyExpectsDouble(my.calculateEither());
I.e., not having to add the getLeft()/getRight()
or + ""
all the time?
Actually, it does not bother me much if I will have to do
their.thirdPartyExpectsDouble(my.calculateEither().getRight());
because I don't have to do it often. But I would like to get rid of the need to call getLeft()
or + ""
when my.calculateEither()
returns a Left
(a String).
Given an either
, it's not hard to see if it represents Right
or Left
, simply by checking which side has a null
.
But the problem is with the type conversion, i.e. the compilation error when thirdPartyExpectsString()
expects a String
but gets an Either
.
I was able to catch the return value of my.calculateEither()
by AspectJ but I could not see a way how to use something like @AfterReturning
advice to make the compiler understand that I want to return my.calculateEither().getLeft()
, i.e a String
....
Any ideas?