gpt4 book ai didi

Java 11 编译器无法识别 main 方法中的静态 BiFunction

转载 作者:行者123 更新时间:2023-12-01 14:10:24 24 4
gpt4 key购买 nike

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

我试图将其设为 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

最佳答案

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

关于Java 11 编译器无法识别 main 方法中的静态 BiFunction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61000001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com