为什么不能为Java中的var关键字分配一个lambda表达式? [英] Why can't the var keyword in Java be assigned a lambda expression?

查看:78
本文介绍了为什么不能为Java中的var关键字分配一个lambda表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

允许在Java 10中为var分配字符串,例如:

It is allowed to assign var in Java 10 with a string like:

var foo = "boo";

虽然不允许为其分配lambda表达式,例如:

While it is not allowed to assign it with a lambda expression such as:

var predicateVar = apple -> apple.getColor().equals("red");

为什么当可以推断诸如StringArrayList,用户类之类的其余部分时,为什么不能推断出lambda或方法引用类型?

Why can't it infer a lambda or method reference type when it can infer the rest like String, ArrayList, user class, etc.?

推荐答案

来自本地变量类型推断JEP :

实质上,推理过程只是将变量赋予其初始化程序表达式的类型.一些细微之处:

The inference process, substantially, just gives the variable the type of its initializer expression. Some subtleties:

  • 初始化器没有目标类型(因为我们尚未推断出它).需要这种类型的多边形表达式(例如 lambdas ,方法引用和数组初始化程序)将触发错误.
  • The initializer has no target type (because we haven't inferred it yet). Poly expressions that require such a type, like lambdas, method references, and array initializers, will trigger an error.

由于lambda表达式本身没有类型,因此无法为var推断出来.

Because a lambda expression by itself does not have a type, it can not be inferred for var.

...同样,可以设置默认规则.

... Similarly, a default rule could be set.

当然,您可以想出一种方法来解决此限制.为何开发人员决定不这样做,实际上取决于猜测,除非参与决策的人可以在这里回答. (更新:在在此处回答.)如果您仍然有兴趣,可以在openjdk邮件列表之一中询问它. : http://mail.openjdk.java.net/mailman/listinfo

Sure, you can come up with a way to work around this limitation. Why the developers made the decision not to do that is really up to speculation, unless someone who was part of the decision making can answer here. (Update: answered here.) If you're interested anyway, you could ask about it on one of the openjdk mailing lists: http://mail.openjdk.java.net/mailman/listinfo

如果我猜的话,他们可能不想将var上下文中的lambda推断与一组特定的功能接口类型相关联,这将排除任何第三方功能接口类型.更好的解决方案是推断可以转换为兼容功能接口类型的通用功能类型(即(Apple) -> boolean).但是JVM没有这种函数类型,并且在创建lambda表达式的项目期间已经做出了不实现它们的决定.同样,如果您对具体原因感兴趣,请询问开发人员.

If I were to guess, they probably didn't want to tie lambda inference in the context of var to a specific set of functional interface types, which would exclude any third party functional interface types. A better solution would be to infer a generic function type (i.e. (Apple) -> boolean) that can than be converted to a compatible functional interface type. But the JVM does not have such function types, and the decision to not implement them was already made during the project that created lambda expressions. Again if you're interested in concrete reasons, ask the devs.

这篇关于为什么不能为Java中的var关键字分配一个lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆