[英]Parsing scalaz.Validation in Java
I have a scala function with the following signature: 我有一个带有以下签名的scala函数:
def getValue: Validation[ Throwable, String ]
Now, I want to process in Java the result (say res
) of calling this function. 现在,我想在Java中处理调用此函数的结果(例如
res
)。
I can call res.isSuccess()
and res.isFailure()
but how do I extract the underlying Throwable
or success String
? 我可以调用
res.isSuccess()
和res.isFailure()
但是如何提取底层的Throwable
或成功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) 我尝试了但是测试
(res instanceof scalaz.Failure)
导致scalaz.Failure cannot be resolved to a type
(scala和scalaz jar可见)
Is there a generic way of doing this for Validation
, Option
, Either
, etc... ? 有没有一种通用的方法来
Validation
, Option
, Either
......等等?
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). 编辑我意识到我可能会使用
fold
但这将导致Java中许多丑陋的样板代码(不需要更多)。 Anything better looking ? 有什么好看的吗?
Success
and Failure
are both case classes: Success
和Failure
都是案例类:
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
). 对于
Option
和Either
您可以使用get
方法(在Either
的情况下进行left
投影或right
投影之后)。
If at all possible it's probably cleaner to do this kind of unwrapping with a fold
, etc. on the Scala side, though. 但是,如果可能的话,在Scala方面进行
fold
等的这种展开可能更加清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.