Java 11编译器无法识别main方法中的静态双函数

Java 11编译器无法识别main方法中的静态双函数,java,lambda,compiler-errors,functional-programming,Java,Lambda,Compiler Errors,Functional Programming,我一直在尝试用Java进行函数式编程。然而,当我在类中使用函数接口作为第一类变量时,我的变量在编译时不会被识别 我曾尝试将其设置为main中的局部变量,但收到了相同的结果 我是不是遗漏了什么 代码: 版本信息: javac 11.0.6 openjdk 11.0.6 2020-01-14 Ubuntu 18.04 调用函数接口没有特殊的语法 要进行调用,需要正常调用实际函数 System.out.println(Question.add.apply(1, 2)); add变量不需要限定 Sy

我一直在尝试用Java进行函数式编程。然而,当我在类中使用函数接口作为第一类变量时,我的变量在编译时不会被识别

我曾尝试将其设置为
main
中的局部变量,但收到了相同的结果

我是不是遗漏了什么

代码:

版本信息:

javac 11.0.6
openjdk 11.0.6 2020-01-14
Ubuntu 18.04

调用函数接口没有特殊的语法

要进行调用,需要正常调用实际函数

System.out.println(Question.add.apply(1, 2));
add
变量不需要限定

System.out.println(add.apply(1, 2));

这并不是说它不识别
add
,而是
add
不是一种方法——它是
BiConsumer
的一个实例。您不能像调用方法一样调用它,您需要调用它的
apply
方法:

System.out.println(Question.add.apply(1,2));
// Here -----------------------^
Question.add(1,2)
是一个方法调用,而
add
是一个字段

class Question {
  static final BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;

  static final int add(int a, int b) {
    return add.apply(a, b);
  }

  public static void main(String[] args) {
    // calls the method
    System.out.println(Question.add(1,2));

    // gets the field and calls BiFunction's method
    System.out.println(Question.add.apply(1,2));
  }
}
课堂提问{
静态最终双功能加法=(a,b)->a+b;
静态最终整数相加(整数a、整数b){
返回添加应用(a、b);
}
公共静态void main(字符串[]args){
//调用该方法
系统输出打印LN(问题添加(1,2));
//获取字段并调用双函数的方法
System.out.println(问题.添加.应用(1,2));
}
}

太棒了。我完全忘记了调用函数需要apply!非常感谢你
静态最终int add(int a,int b)
本身就是一个bi函数,如果你这样看的话。@Naman没错,我正要写
返回a+b
,但是,等等,让我们重新使用代码:)
System.out.println(add.apply(1, 2));
System.out.println(Question.add.apply(1,2));
// Here -----------------------^
class Question {
  static final BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;

  static final int add(int a, int b) {
    return add.apply(a, b);
  }

  public static void main(String[] args) {
    // calls the method
    System.out.println(Question.add(1,2));

    // gets the field and calls BiFunction's method
    System.out.println(Question.add.apply(1,2));
  }
}