为什么Java 8引入了新的“::”方法参考的运算符? [英] Why did Java 8 introduce a new "::" operator for method references?

查看:130
本文介绍了为什么Java 8引入了新的“::”方法参考的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中,方法引用是使用 :: 运算符完成的。

In Java 8 method references are done using the :: operator.

例如

// Class that provides the functionality via it's static method
public class AddableUtil {
  public static int addThemUp(int i1, int i2){
    return i1+i2;
  }
}

// Test class
public class AddableTest {
  // Lambda expression using static method on a separate class
  IAddable addableViaMethodReference = AddableUtil::addThemUp;
  ...
}

你可以看到 addableViaMethodReference 现在就像 AddableUtil :: addThemUp 的别名。所以 addableViaMethodReference()将执行与 AddableUtil.addThemUp()相同的操作并返回相同的值。

You can see that the addableViaMethodReference now acts like an alias to AddableUtil::addThemUp. So addableViaMethodReference() will perform the same action as AddableUtil.addThemUp() and return the same value.

为什么他们选择引入新运营商而不是使用现有运营商?我的意思是,当函数名以()结尾时执行函数,并在没有尾随()

Why did they choose to introduce a new operator instead of using an existing one ? I mean, execute a function when the function name ends with () and return the function reference when there is no trailing ().

方法执行

AddableUtil.addThemUp();

方法参考

AddableUtil.addThemUp;

这不是更简单直观吗? AFAIK, AddableUtil.addThemUp 当前没有(Java 7)用于任何其他目的并引发编译错误。为什么不使用这个机会而不是创建一个全新的运算符?

Wouldn't this be much simpler and intuitive ? AFAIK, AddableUtil.addThemUp doesn't currently (Java 7) serve any other purpose and throws a compilation error. Why not use that opportunity instead of creating an entirely new operator ?

推荐答案

下面的代码在Java 8中编译得很好,但是没有新的运算符会有歧义:

The following piece of code compiles fine in Java 8, but would be ambiguous without a new operator:

import java.util.function.IntBinaryOperator;

public class A {

  public static IntBinaryOperator addThemUp;

  public static int addThemUp(int i1, int i2) {
    return i1 + i2;
  }

  public static void main(String[] args) throws Exception {
    IntBinaryOperator operator = A::addThemUp;
  }
}

目前还不清楚是否 A.addThemUp 引用公共 IntBinaryOperator 字段或尝试创建方法引用。

It wouldn't be clear whether A.addThemUp refers to the public IntBinaryOperator field or is an attempt to create a method reference.

是的,这有点做作。但是你不能允许编程语言语法中的边缘情况

这篇关于为什么Java 8引入了新的“::”方法参考的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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