简体   繁体   中英

Parsing scalaz.Validation in Java

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM