Why do I need a functional Interface to work with lambdas?

前端 未结 6 2166
故里飘歌
故里飘歌 2020-11-27 15:09

I think this question is already somewhere out there, but I wasn\'t able to find it.

I don\'t understand, why it\'s necessary to have a functional interface to work

6条回答
  •  天命终不由人
    2020-11-27 15:46

    The most important reason why they must contain only one method, is that confusion is easily possible otherwise. If multiple methods were allowed in the interface, which method should a lambda pick if the argument lists are the same ?

    interface TestInterface {
        void first();
        void second(); // this is only distinguished from first() by method name
        String third(); // maybe you could say in this instance "well the return type is different"
        Object fourth(); // but a String is an Object, too !
    }
    
    void test() {
        // which method are you implementing, first or second ?
        TestInterface a = () -> System.out.println("Ido mein ado mein");
        // which method are you implementing, third or fourth ?
        TestInterface b = () -> "Ido mein ado mein";
    }
    

提交回复
热议问题