我正在玩java8 lambdas,我遇到了编译器错误,我没想到.
假设我有一个函数interface A,一个abstract class B和一个class C重载方法,它们可以采用A或B作为参数:
public interface A {
void invoke(String arg);
}
public abstract class B {
public abstract void invoke(String arg);
}
public class C {
public void apply(A x) { }
public B apply(B x) { return x; }
}
Run Code Online (Sandbox Code Playgroud)
然后我可以传入一个lambda c.apply,它正确地解决了c.apply(A).
C c = new C();
c.apply(x -> System.out.println(x));
Run Code Online (Sandbox Code Playgroud)
但是当我更改B作为泛型版本的参数的重载时,编译器报告两个重载是不明确的.
public class C {
public void apply(A x) { …Run Code Online (Sandbox Code Playgroud) 我遇到一个奇怪的问题,方法引用Thread::sleep是模糊的,但具有相同签名的方法不是.
package test;
public class Test
{
public static void main(String[] args)
{
foo(Test::sleep, 1000L); //fine
foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
foo(Thread::sleep, 1000L); //error
}
public static void sleep(long millis) throws InterruptedException
{
Thread.sleep(millis);
}
public static <P, R> void foo(Foo<P, R> function, P param) {}
public static <P> void foo(FooVoid<P> function, P param) {}
@FunctionalInterface
public interface Foo<P, R> {
R call(P param1) throws Exception;
}
@FunctionalInterface
public interface FooVoid<P> {
void call(P param1) throws Exception;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这两个错误: …
使用Java 8,我得到以下代码的编译器错误:
public class Ambiguous {
public static void call() {
SomeDataClass data = new SomeDataClass();
callee(data, SomeDataClass::getString);
// compiler errors:
// 1. at callee method name:
// The method callee(SomeDataClass, Function<SomeDataClass,String>) is ambiguous for the type Ambiguous
// 2. at lambda:
// Type mismatch: cannot convert from boolean to String
callee(data, d -> d.getRandom() > 0.5);
}
public static void callee(SomeDataClass data, Function<SomeDataClass, String> extractString) {
System.out.println(extractString.apply(data));
}
public static void callee(SomeDataClass data, Predicate<SomeDataClass> check) {
System.out.println(check.test(data));
}
} …Run Code Online (Sandbox Code Playgroud)