【发布时间】:2017-04-02 15:44:49
【问题描述】:
我有一个类可以在 Windows 中编译,但不能在 Linux 中编译。
不编译的方法是mapA。
我得到的错误是:“错误:类型参数 B 不在类型变量 B 的范围内”。
为什么 Windows 接受我的代码而 Linux 不接受?
我可以以某种方式禁用此错误吗?
这是课程:
/** Either an A or a B. C is some common supertype of A and B. */
public class EitherOr<C, A extends C, B extends C>
{
private final boolean isA;
private final A a;
private final B b;
protected EitherOr(boolean isA, A a, B b)
{
this.isA = isA;
this.a = a;
this.b = b;
}
/**
* If f(A) is of type D,
* maps an EitherOr<C, A, B> to an EitherOr<E, f(A), B>,
* where E is some common supertype of D and B.
*/
public<E, D extends E> EitherOr<E, D, B> mapA(Function<A, D> f)
{
return (EitherOr<E, D, B>)(isA ? ofA(f.apply(a)) : ofB(b));
}
/** Creates an EitherOr<C, A, B> which is actually an A */
public static<C, A extends C, B extends C> EitherOr<C, A, B> ofA(A a) {...}
/** Creates an EitherOr<C, A, B> which is actually a B */
public static<C, A extends C, B extends C> EitherOr<C, A, B> ofB(B b) {...}
/** If is A, returns a, else throws an exception. */
public A getA() {...}
/** If is B, returns b, else throws an exception. */
public B getB() {...}
public C getValue() {return isA ? a : b;}
...
}
【问题讨论】:
-
错误在哪里?在方法签名上,还是在方法中?
-
我高度怀疑 Windows 和 Linux 中的代码不一样。
-
注意:最好将条件表达式写成显式的
if/else。那里的类型推断很可能有点麻烦(正如演员表所证明的那样)。 -
@m0skit0: 或者编译器生成或设置不同
-
我怀疑
C的价值。我看到它被用作getValue()方法的返回值;但是与静态方法static <C> C getValue(EitherOr<? extends C, ? extends C> eo)方法相比,它需要携带很多额外的语法包袱(见我的回答here)。