Java 11 compiler not recognizing static BiFunction in main method

Viewed 402

I've been trying to give functional programming in Java a try. However, when I use a functional interface in a class as a first-class variable, my variables are not recognized when I compile.

I have attempted to make it a local variable within main, but received the same results.

Am I missing something here?

Code:

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

Error Received:

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

Version Info:

javac 11.0.6
openjdk 11.0.6 2020-01-14
Ubuntu 18.04
3 Answers

There is no special syntax for calling functional interfaces.

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

To make the call requires invoking the actual function as normal.

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

The add variable doesn't need to be qualified.

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

It's not that it doesn't recognize add, it's that add isn't a method - it's an instance of BiConsumer. You can't call it as if it were a method, you need to call its apply method:

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

Question.add(1,2) is a method call, while add is a field.

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