【问题标题】:Java 11 compiler not recognizing static BiFunction in main methodJava 11 编译器无法识别 main 方法中的静态 BiFunction
【发布时间】:2020-04-02 19:54:08
【问题描述】:

我一直在尝试用 Java 进行函数式编程。但是,当我在类中使用函数式接口作为一等变量时,我的变量在编译时无法识别。

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

我错过了什么吗?

代码:

import java.util.function.BiFunction;

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

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

收到错误:

Question.java:7: error: cannot find symbol
        System.out.println(Question.add(1,2));
                                   ^
  symbol:   method add(int,int)
  location: class Question

版本信息:

javac 11.0.6
openjdk 11.0.6 2020-01-14
Ubuntu 18.04

【问题讨论】:

    标签: java lambda compiler-errors functional-programming


    【解决方案1】:

    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));
      }
    }
    

    【讨论】:

    • 太棒了。我完全忘记了 apply 是调用该函数所必需的!非常感谢!
    • static final int add(int a, int b) 本身就是一个双功能,如果你这样看的话。
    • @Naman 没错,我正要写return a + b,但是,等等,让我们重用代码:)
    【解决方案2】:

    并不是它不识别add,而是add 不是一个方法——它是BiConsumer 的一个实例。你不能把它当成一个方法来调用,你需要调用它的apply方法:

    System.out.println(Question.add.apply(1,2));
    // Here -----------------------^
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      add 变量不需要限定。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-28
        • 2011-04-28
        • 1970-01-01
        • 2020-06-15
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多