reference to method is ambiguous when migrating from java8 to java9

[亡魂溺海] 提交于 2019-12-03 02:41:46
Holger

This is a bug.

It has been reported with bug ID : JDK-8195598


I simplified your example further:

public class Q48227496 {
    public CompletableFuture<?> test() {
        return ok(() -> System.out.append("aaa"));
    }
    public <T> CompletableFuture<T> ok(Supplier<T> action) {
        return CompletableFuture.supplyAsync(action);
    }
    public <T> CompletableFuture<T> ok(T body) {
        return CompletableFuture.completedFuture(body);
    }
    public CompletableFuture<Void> ok(Runnable action) {
        return CompletableFuture.runAsync(action);
    }
}

This fails in the release version of Java 9 with “reference to ok is ambiguous”, stating “both method <T>ok(Supplier<T>) in Q48227496 and method ok(Runnable) in Q48227496 match”.

But just changing the order of the methods

public class Q48227496 {
    public CompletableFuture<?> test() {
        return ok(() -> System.out.append("aaa"));
    }
    public <T> CompletableFuture<T> ok(T body) {
        return CompletableFuture.completedFuture(body);
    }
    public <T> CompletableFuture<T> ok(Supplier<T> action) {
        return CompletableFuture.supplyAsync(action);
    }
    public CompletableFuture<Void> ok(Runnable action) {
        return CompletableFuture.runAsync(action);
    }
}

causes the compiler to accept the code without any errors.

So, obviously, this is a compiler bug as the order of the method declarations should never have an impact on the validity of the code.

Also, removing the ok(T) method makes the code accepted.

Note that whenever the compiler accepts the code, it considers ok(Supplier) to be more specific than ok(Runnable), which is the expected behavior for a function parameter that matches both.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!