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

前端 未结 6 2140
故里飘歌
故里飘歌 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 16:06

    You do not have to create a functional interface in order to create lambda function. The interface allow you to create instance for future function invocation.

    In your case you could use already existing interface Runable

    Runnable r = () -> System.out.println("Hans");

    and then call

    r.run();

    You can think of lambda -> as only short hand for:

    Runnable r = new Runnable() {
         void run() {
              System.out.println("Hans");`
         }
    }
    

    With lambda you do not need the anonymous class, that is created under the hood in above example.

    But this has some limitation, in order to figure out what method should be called interface used with lambdas must be SAM (Single Abstract Method). Then we have only one method.

    For more detailed explanation read:

    Introduction to Functional Interfaces – A Concept Recreated in Java 8

提交回复
热议问题