为什么方法引用需要类型转换为 Function 接口?
Why does method reference needs a type casting to a Function interface?
在此代码片段中,我的 IDE (IDEA Intellij 社区) 建议将方法引用转换为函数接口。
这是为什么?
public class MethodReferences {
public static void main(String[] strings) {
Function<String, Integer> f = Integer::parseInt;
Predicate<Person> personPredicate = p->convert(p.getAge(),Integer::parseInt) >10;
//This is fine
System.out.println(convert("123", f));
//This is fine
System.out.println(convert("123", (Function<String, Integer>) Integer::parseInt));
//This is NOT
System.out.println(convert("123", Integer::parseInt)); //x1
}
private static <T, S> T convert(S s, Function<S, T> stFunction) {
return stFunction.apply(s);
}
}
我在 x1
行得到的错误消息是:
Error:(20, 19) java: reference to println is ambiguous
both method println(char[]) in java.io.PrintStream and method println(java.lang.String) in java.io.PrintStream match
Error:(20, 35) java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Integer
upper bound(s): char[],java.lang.Object
不接受,因为 parseInt 方法有两种不同的类型。
其中一个只接受一个 String
参数,另一个接受一个 String
和一个 int
类型:
static int parseInt(String s)
static int parseInt(String s, int radix)
在您的代码中,您使用的是第二个,因此您应该转换为第二个。据我所知,在 Eclipse 中,IDE 会自动理解它属于什么;但在 IntelliJ 中,您应该进行类型转换以确保安全和良好的编程。
在此代码片段中,我的 IDE (IDEA Intellij 社区) 建议将方法引用转换为函数接口。
这是为什么?
public class MethodReferences {
public static void main(String[] strings) {
Function<String, Integer> f = Integer::parseInt;
Predicate<Person> personPredicate = p->convert(p.getAge(),Integer::parseInt) >10;
//This is fine
System.out.println(convert("123", f));
//This is fine
System.out.println(convert("123", (Function<String, Integer>) Integer::parseInt));
//This is NOT
System.out.println(convert("123", Integer::parseInt)); //x1
}
private static <T, S> T convert(S s, Function<S, T> stFunction) {
return stFunction.apply(s);
}
}
我在 x1
行得到的错误消息是:
Error:(20, 19) java: reference to println is ambiguous
both method println(char[]) in java.io.PrintStream and method println(java.lang.String) in java.io.PrintStream match
Error:(20, 35) java: incompatible types: inferred type does not conform to upper bound(s)
inferred: java.lang.Integer
upper bound(s): char[],java.lang.Object
不接受,因为 parseInt 方法有两种不同的类型。
其中一个只接受一个 String
参数,另一个接受一个 String
和一个 int
类型:
static int parseInt(String s)
static int parseInt(String s, int radix)
在您的代码中,您使用的是第二个,因此您应该转换为第二个。据我所知,在 Eclipse 中,IDE 会自动理解它属于什么;但在 IntelliJ 中,您应该进行类型转换以确保安全和良好的编程。