Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the interface is functional in Java? [duplicate]

As everybody knows, Java 8 have introduced functional programming to Java developers.

Such interfaces as Comparator, Runnable, Callable and so on are functional.

As follows from definition: functional interfaces are interfaces that have only a single abstract method.

But for example the same interface Comparator have more than one abstract methods:

int compare(T o1, T o2);

boolean equals(Object obj); // inherited from Object class

// and a lot of concrete methods more

Well, is there any strict rule of how to determine if the interface is functional, so that it can be used as the assignment target for a lambda expression or method reference?

like image 748
DimaSan Avatar asked Sep 23 '16 08:09

DimaSan


1 Answers

From the JLS §9.8 (highlighting mine):

A functional interface is an interface that has just one abstract method (aside from the methods of Object)

The rationale is

  1. to use the interface, you have to instantiate it. Every instantiation necessarily inherits from Object, and thus implements these abstract methods anyway.

    The other method - boolean equals(Object) - is an explicit declaration of an abstract method that would otherwise be implicitly declared, and will be automatically implemented by every class that implements the interface.

  2. As a functional interface, it is very unlikely that you want to call a method that is defined by Object. Thus, these methods do not count when searching for a method to call (because the method of functional interfaces can be called without naming that method).

    This is to allow functional treatment of an interface like java.util.Comparator<T> that declares multiple abstract methods of which only one is really "new" - int compare(T,T).

like image 119
Martin Nyolt Avatar answered Sep 23 '22 19:09

Martin Nyolt