在Java中,为什么AREN' t默认函数与返回类型的协变,而与参数类型相反

发布于 2025-01-21 18:58:56 字数 1096 浏览 2 评论 0原文

请查看以下代码,

如果函数与参数类型违反了函数,则该编译器会依据,因此编译器会投诉:

  // 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文