我使用Java中的本土实施Either
,其中有一个方法是这样的:这个分支为什么会打破类型推断?
public static <L, R> Either<L, R> left(final L value);
public static <L, R> Either<L, R> right(final R value);
public <T> T fold(
final Function<? super L, ? extends T> leftFunction,
final Function<? super R, ? extends T> rightFunction);
这两种方法编制和精细工作:
Either<Foo, Bar> rightToLeft() {
Either<Foo, Bar> input = Either.right(new Bar());
return input.fold(
l -> null,
r -> Either.left(new Foo())
);
}
Either<Foo, Bar> rightToRight() {
Either<Foo, Bar> input = Either.right(new Bar());
return input.fold(
l -> null,
r -> Either.right(new Bar())
);
}
此方法不编译:
Either<Foo, Bar> rightToLeftOrRightConditionally() {
Either<Foo, Bar> input = Either.right(new Bar());
return input.fold(
l -> null,
r -> {
if (r.equals("x")) {
return Either.left(new Foo());
}
return Either.right(new Bar());
});
}
错误:
incompatible types: inferred type does not conform to upper bound(s)
inferred: Either<? extends Object,? extends Object>
upper bound(s): Either<Foo,Bar>,java.lang.Object
(我修剪出来的包预选赛,使错误更易读)
我可以把它通过指定类型的编译:
if (r.equals("x")) {
return Either.<Foo, Bar> left(new Foo());
}
return Either.<Foo, Bar> right(new Bar());
但为什么我需要?我怎样才能避免这种代码混乱?
因为编译器就会犯糊涂?您应该在左侧和右侧发布代码 – 2017-02-27 11:52:18
@RC。我添加了'left()'和'right()'的签名 – slim
无法重现。在'javac'和eclipse中这对我来说都很好。 –