John C :
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
Andrew Tobilko :
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));
}
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=401217&siteId=1