What are functional interfaces used for in Java 8?

前端 未结 10 2124
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:46

    @FunctionalInterface is a new annotation are released with Java 8 and provide target types for lambda expressions and it used on compilation time checking of your code.

    When you want to use it :

    1- Your interface must not have more than one abstract methods, otherwise compilation error will be given.

    1- Your interface Should be pure, which means functional interface is intended to be implemented by stateless classes, exmple of pure is Comparator interface because its not depend on the implementers state, in this case No compilation error will be given, but in many cases you will not be able to use lambda with this kind of interfaces

    The java.util.function package contains various general purpose functional interfaces such as Predicate, Consumer, Function, and Supplier.

    Also please note that you can use lambdas without this annotation.

提交回复
热议问题