Why does a lambda change overloads when it throws a runtime exception?

前端 未结 5 1153
心在旅途
心在旅途 2021-01-31 02:14

Bear with me, the introduction is a bit long-winded but this is an interesting puzzle.

I have this code:

public class Testcase {
    public static void m         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 02:59

    It appears that when throwing an Exception, the compiler chooses the interface which returns a reference.

    interface Calls {
        void add(Runnable run);
    
        void add(IntSupplier supplier);
    }
    
    // Ambiguous call
    calls.add(() -> {
            System.out.println("hi");
            throw new IllegalArgumentException();
        });
    

    However

    interface Calls {
        void add(Runnable run);
    
        void add(IntSupplier supplier);
    
        void add(Supplier supplier);
    }
    

    complains

    Error:(24, 14) java: reference to add is ambiguous both method add(java.util.function.IntSupplier) in Main.Calls and method add(java.util.function.Supplier) in Main.Calls match

    Lastly

    interface Calls {
        void add(Runnable run);
    
        void add(Supplier supplier);
    }
    

    compiles fine.

    So weirdly;

    • void vs int is ambiguous
    • int vs Integer is ambiguous
    • void vs Integer is NOT ambiguous.

    So I figure something is broken here.

    I have sent a bug report to oracle.

提交回复
热议问题