What are functional interfaces used for in Java 8?

前端 未结 10 2248
Happy的楠姐
Happy的楠姐 2020-11-22 09:08

I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions.

Java 8 provides

10条回答
  •  误落风尘
    2020-11-22 09:50

    The documentation makes indeed a difference between the purpose

    An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.

    and the use case

    Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

    whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”

    Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:

    JLS §9.8. Functional Interfaces:

    In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).

    So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).

    So in one sentence, no, there is no other use case for it in Java 8.

提交回复
热议问题