这里是Test.java的代码:
import java.util.function.Consumer;
import java.util.function.Function;
public class Test{
private static void test(Function function){
System.out.println("function");
}
private static void test(Consumer consumer){
System.out.println("consumer");
}
public static void main(String[] args) {
/// arrow1: no error
test(i-> {System.out.println();});
/// arrow2: no error
test((Object i)-> System.out.println());
/// arrow3: error: reference to test is ambiguous
test(i-> System.out.println());
/// arrow4: error: incompatible types: bad return type in lambda expression
Function function = i-> System.out.println();
}
}
Arrow3 推断箭头函数不是右函数,但 arrow4 可以。
arrow3: javac Test.java
Test.java:18: error: reference to test is ambiguous
test(i-> System.out.println());
^
both method test(Function) in Test and method test(Consumer) in Test match
Test.java:18: error: incompatible types: bad return type in lambda expression
test(i-> System.out.println());
^
void cannot be converted to Object
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
arrow4: javac Test.java
Test.java:20: error: incompatible types: bad return type in lambda expression
Function function = i-> System.out.println();
^
void cannot be converted to Object
1 error
我是Java新手,问过同事和ChatGPT,都没有得到满意的答复。我想知道是Java的BUG还是我不懂Java的语法,谢谢!