What are functional interfaces?

Asked

Viewed 4,750 times

10

What are functional interfaces in Java?

This concept already existed or emerged from version 8 of Java?

2 answers

15


The interfaces in Java 8 have gained many new and powerful features, such as abstract methods and default.

Specifically talking about the Interfaces Funcionais, the concept is of an Interface that contains only an abstract method, as is the case of Runnable, for example. This type of Interface is used in specific situations, being common instantiation is through an anonymous class.

Definition facilitated through annotation

Starting with Java 8, these interfaces can be annotated with @FunctionalInterface:

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

When declaring more than one method (except the methods already present in the Object class), the compiler will complain, avoiding unnecessary errors.

Where this is used?

Lambda expressions

With the guarantee that the Interface only has one method, this concept becomes useful when combined, for example, with a lambda expression.

Suppose we have a method with the signature invoke(Runnable r). Before Java 8, we could use a new Runnable and overwrite the method run() as follows:

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Thread executando...");
    }
};
invoke(r);

In Java 8, the equivalent code becomes much simpler:

invoke(() -> System.out.println("Running"));

An implementation of Runnable is created, the content of which run() is the value of the expression lambda.

References to methods

Java 8 also brings the concept of references to methods. This is a great way to reuse code and avoid creating unnecessary classes, especially in the case of classes with a method that serves only to delegate execution to another.

For example, instead of creating a Comparator different each time we need to sort a list or array, we can only pass a reference to the method that makes the comparison. Consider the following implementation:

class ComparisonProvider {
    public int compareByName(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }

    public int compareByAge(Person a, Person b) {
        return a.getBirthday().compareTo(b.getBirthday());
    }
}

We can reference one of the methods to sort an array, like this:

ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);

As the second parameter of the method sort() gets a Comparator, which is a Functional Interface, Java can create an implementation for it with the method passed as reference.

References for reading

-1

There is also... Integrated functional interfaces

In addition to the unique abstract method interfaces already mentioned, JDK 8 includes several new functional interfaces. The most common are Function, Predicate, and Consumer, which are defined in the java.util.Function package. The Stream map method uses Function as a parameter. Similarly, filter uses Predicate and foreach uses Consumer. The package also has other functional interfaces like Supplier, Biconsumer and Bifunction.

It is possible to use an integrated functional interface as a parameter for our own methods. For example, consider a Device class with methods such as checkout and checkin to indicate if a device is in use. When a user requests a new device, the getFromAvailable method returns a set of available devices or creates a new one if needed.

It is possible to implement a function to lend a device, as follows:

public void borrowDevice(Consumer<Device> use) {
  Device device = getFromAvailable();

  device.checkout();

  try {
    use.accept(device);      
  } finally {
    device.checkin();
  }
}

Here you can find an excellent source of reference...

https://www.ibm.com/developerworks/br/library/j-java8idioms7/index.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.