Reputation: 29814
I have a scala function with the following signature:
def getValue: Validation[ Throwable, String ]
Now, I want to process in Java the result (say res
) of calling this function.
I can call res.isSuccess()
and res.isFailure()
but how do I extract the underlying Throwable
or success String
?
I tried casting but testing (res instanceof scalaz.Failure)
results in a scalaz.Failure cannot be resolved to a type
(the scala and scalaz jars are visible)
Is there a generic way of doing this for Validation
, Option
, Either
, etc... ?
EDIT I realize I can probably use a fold
but that would lead to a lot of ugly boilerplate code in Java (which does not need more). Anything better looking ?
Upvotes: 3
Views: 329
Reputation: 139038
Success
and Failure
are both case classes:
final case class Success[E, A](a: A) extends Validation[E, A]
final case class Failure[E, A](e: E) extends Validation[E, A]
So you can write the following, for example:
import scalaz.*;
public class Javaz {
public static void main(String[] args) {
Validation<Throwable, String> res = new Success<Throwable, String>("test");
if (res.isSuccess()) {
System.out.println(((Success) res).a());
} else {
System.out.println(((Failure) res).e());
}
}
}
For Option
and Either
you can use the get
method (after taking the left
or right
projection in the case of Either
).
If at all possible it's probably cleaner to do this kind of unwrapping with a fold
, etc. on the Scala side, though.
Upvotes: 4