【发布时间】:2017-02-27 11:48:39
【问题描述】:
我在 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());
但我为什么需要这样做?以及如何避免这种代码混乱?
【问题讨论】:
-
因为编译器弄糊涂了?您应该发布
left和right的代码 -
@RC。我添加了
left()和right()的签名 -
无法重现。在
javac和 eclipse 中,这对我来说都很好。 -
@JornVernee 感谢您的关注。请参阅下面我对 Dmitri 的回复——您使用的是哪个版本的
javac? -
@Slim 我正在使用
javac 1.8.0_101
标签: java type-inference