Tuesday, January 17, 2017

Using @FunctionalInterface annotation

A functional interface has exactly one abstract method, also called, SAM interface (Single Abstract Method). SAM interfaces have a special place in Java 8 because they can be implemented using Lambda expressions or Method references.

@FunctionalInterface annotation allows us to forces a compilation error when an additional, non-overriding abstract method is added to a SAM. Once the SAM contract is broken, the interface could no more be used in Lambda implementations.

BatchConsumer:
package refactor;

import java.util.function.Consumer;

/**
 * A functional interface example
 */
@FunctionalInterface
public interface BatchConsumer<T> extends Consumer<T> {
    default void beforeConsume() {}

    default void afterConsume(){}
}

BatchConsumer contains single abstract method accept() but can contain default methods. The default methods have an implementation and are not abstract so it will still remain a functional interface. If we add one more method to the SAM interface, will result in the below compilation error:
Multiple non-overriding abstract methods found in interface refactor.BatchConsumer.

Batch:
package refactor;

import java.util.Arrays;

public class Batch {

    public static void main(String[] args) {
        consumeIntegers(i -> System.out.println(Arrays.asList(i)));

        consumeIntegers(new BatchConsumer<Integer[]>() {
            public void beforeConsume() {
                System.out.println("before consuming");
            }

            @Override
            public void accept(Integer[] i) {
                System.out.println(Arrays.asList(i));
            }

            public void afterConsume() {
                System.out.println("after consuming");
            }
        });
    }

    private static void consumeIntegers(BatchConsumer<Integer[]> consumer) {
        consumer.beforeConsume();
        consumer.accept(new Integer[]{1, 2, 3, 4});
        consumer.afterConsume();
    }
}

Output:
[1, 2, 3, 4]
before consuming
[1, 2, 3, 4]
after consuming

No comments:

Post a Comment