HRJ*_*HRJ 69 java scala java-8
就像java.util.Optional<T>在Java 8中(有点)等同于Scala的Option[T]类型,是否有相当于Scala的Either[L, R]?
Hol*_*ger 60
EitherJava 8 没有类型,因此您需要自己创建一个或使用某些第三方库.
您可以使用新Optional类型构建此类功能(但请阅读本答案的末尾):
final class Either<L,R>
{
public static <L,R> Either<L,R> left(L value) {
return new Either<>(Optional.of(value), Optional.empty());
}
public static <L,R> Either<L,R> right(R value) {
return new Either<>(Optional.empty(), Optional.of(value));
}
private final Optional<L> left;
private final Optional<R> right;
private Either(Optional<L> l, Optional<R> r) {
left=l;
right=r;
}
public <T> T map(
Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc)
{
return left.<T>map(lFunc).orElseGet(()->right.map(rFunc).get());
}
public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc)
{
return new Either<>(left.map(lFunc),right);
}
public <T> Either<L,T> mapRight(Function<? super R, ? extends T> rFunc)
{
return new Either<>(left, right.map(rFunc));
}
public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc)
{
left.ifPresent(lFunc);
right.ifPresent(rFunc);
}
}
Run Code Online (Sandbox Code Playgroud)
用例示例:
new Random().ints(20, 0, 2).mapToObj(i -> (Either<String,Integer>)(i==0?
Either.left("left value (String)"):
Either.right(42)))
.forEach(either->either.apply(
left ->{ System.out.println("received left value: "+left.substring(11));},
right->{ System.out.println("received right value: 0x"+Integer.toHexString(right));}
));
Run Code Online (Sandbox Code Playgroud)
在回顾中,Optional基于解决方案更像是一个学术范例,但不是推荐的方法.一个问题是null"空" 的处理与"任一"的含义相矛盾.
以下代码显示了一个Either考虑null可能值的代码,因此它严格地"左右",向左或向右,即使值为null:
abstract class Either<L,R>
{
public static <L,R> Either<L,R> left(L value) {
return new Either<L,R>() {
@Override public <T> T map(Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc) {
return lFunc.apply(value);
}
};
}
public static <L,R> Either<L,R> right(R value) {
return new Either<L,R>() {
@Override public <T> T map(Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc) {
return rFunc.apply(value);
}
};
}
private Either() {}
public abstract <T> T map(
Function<? super L, ? extends T> lFunc, Function<? super R, ? extends T> rFunc);
public <T> Either<T,R> mapLeft(Function<? super L, ? extends T> lFunc) {
return this.<Either<T,R>>map(t -> left(lFunc.apply(t)), t -> (Either<T,R>)this);
}
public <T> Either<L,T> mapRight(Function<? super R, ? extends T> lFunc) {
return this.<Either<L,T>>map(t -> (Either<L,T>)this, t -> right(lFunc.apply(t)));
}
public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc) {
map(consume(lFunc), consume(rFunc));
}
private <T> Function<T,Void> consume(Consumer<T> c) {
return t -> { c.accept(t); return null; };
}
}
Run Code Online (Sandbox Code Playgroud)
null只需Objects.requireNonNull(value)在两种工厂方法的开头插入一个,就可以很容易地将其改为严格拒绝.同样,添加对空的支持也是可以想象的.
whi*_*win 22
在撰写本文时,vavr(以前称为javaslang)可能是最受欢迎的Java 8函数库.在我的另一个答案中,它非常类似于lambda-companion的Either.
Either<String,Integer> value = compute().right().map(i -> i * 2).toEither();
Run Code Online (Sandbox Code Playgroud)
cyclops-react有一个'正确'的偏见,要么被称为Xor.
Xor.primary("hello")
.map(s->s+" world")
//Primary["hello world"]
Xor.secondary("hello")
.map(s->s+" world")
//Secondary["hello"]
Xor.secondary("hello")
.swap()
.map(s->s+" world")
//Primary["hello world"]
Xor.accumulateSecondary(ListX.of(Xor.secondary("failed1"),
Xor.secondary("failed2"),
Xor.primary("success")),
Semigroups.stringConcat)
//failed1failed2
Run Code Online (Sandbox Code Playgroud)
还有一个相关的类型Ior的可作为任一或tuple2行动.
不,没有。
Java语言开发人员明确指出类型,如Option<T>旨在仅作为临时值(例如,在流操作的结果),因此,尽管他们是同样的事情,在其他语言中,他们不应该被使用,因为它们在其他使用语言。因此,不存在这样的情况就不足为奇了,Either因为它不会像自然地那样自然发生(例如,通过流操作)Optional。
Either在小型库“ ambivalence”中有一个独立的实现:http : //github.com/poetix/ambivalence
您可以从Maven Central获得它:
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>ambivalence</artifactId>
<version>0.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
lambda-companion有一个Either类型(以及一些其他功能类型,例如Try)
<dependency>
<groupId>no.finn.lambda</groupId>
<artifactId>lambda-companion</artifactId>
<version>0.25</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
使用它很容易:
final String myValue = Either.right("example").fold(failure -> handleFailure(failure), Function.identity())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37528 次 |
| 最近记录: |