在Java中,为什么AREN' t默认函数与返回类型的协变,而与参数类型相反
请查看以下代码,
如果函数与参数类型违反了函数,则该编译器会依据,因此编译器会投诉:
// contravariant with the parameter type
final Function<Object, Number> objToNUmberfoo = (v) -> 2;
giveMeAFunction(objToNUmberfoo); // THIS GIVES A COMPILER ERROR
public void giveMeAFunction(Function<Integer, Number> foo)
{
// do something
}
的是协方差:
// covariant with the return type
final Function<Integer, BigDecimal> intToBigDecimal = (v) -> 2;
giveMeAFunction2(intToBigDecimal); // THIS GIVES A COMPILER ERROR
public void giveMeAFunction2(Function<Integer, Number> foo)
{
// do something
}
要解决编译器错误,我们应该分别声明该方法
public void giveMeAFunction2(Function<? super Integer, Number> foo)
{
// do something
}
:
public void giveMeAFunction2(Function<Integer, ? extends Number> foo)
{
// do something
}
同样 真的不到达这里是为什么Java编译器默认不允许它?
我想不出任何情况,这在运行时不安全...也许我在这里错了?
更重要的是,这会带来什么后果?
为什么我们需要明确选择这一点?
Take a look at the following code
If Functions were contravariant with the parameter type, this would work, since they are not, the compiler complains:
// contravariant with the parameter type
final Function<Object, Number> objToNUmberfoo = (v) -> 2;
giveMeAFunction(objToNUmberfoo); // THIS GIVES A COMPILER ERROR
public void giveMeAFunction(Function<Integer, Number> foo)
{
// do something
}
Same goes here for covariance:
// covariant with the return type
final Function<Integer, BigDecimal> intToBigDecimal = (v) -> 2;
giveMeAFunction2(intToBigDecimal); // THIS GIVES A COMPILER ERROR
public void giveMeAFunction2(Function<Integer, Number> foo)
{
// do something
}
To fix the compiler errors we should declare the methods respectively:
public void giveMeAFunction2(Function<? super Integer, Number> foo)
{
// do something
}
and
public void giveMeAFunction2(Function<Integer, ? extends Number> foo)
{
// do something
}
What I really don't get here is why isn't the java compiler allowing it by default ?
I cannot think of any situation where this wouldn’t be safe at runtime...maybe I am wrong here ?
And more importantly what would be the consequences of that ?
Why we need to explicitly opt in for that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论