Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Comparable Interface a FunctionalInterface?

Tags:

java

I am using decompiler tools when I look at Comparable it has one abstract method and not have FunctionalInterface annotation

public interface Comparable<T> {
    int compareTo(T var1);
}

same like Comparator, but comparator have FunctionalInterface annotation

    @FunctionalInterface
    public interface Comparator<T> {
    int compare(T var1, T var2);
    ... 
}
like image 701
yali Avatar asked Dec 08 '22 11:12

yali


2 Answers

Is it a FunctionalInterface? No. Comparable doesn't have that annotation.

Is it a functional interface? Yes. From the definition in the language spec:

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

Will it be treated as a FunctionalInterface? Yes:

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

Is it logically a functional interface? No: Comparable doesn't represent a function. It is more like a trait of an object. "This thing can be compared", rather than "this thing does the comparing".

Is there any practical use of it as a functional interface? I would claim there is no obvious use, as evidenced by the fact you will rarely (if ever) see Comparable<Something> being used as the type of a variable, parameter or field; only in extends or implements clauses, and in the bounds of type variables.

like image 96
Andy Turner Avatar answered Dec 28 '22 05:12

Andy Turner


Literally Comparable is a functional interface as it declares one and only one abstract method.
But annotating it with @FunctionalInterface would mean that it is documented to be used as a functional interface while that is not the case at all.
The JLS points out that :

9.6.4.9. @FunctionalInterface

Because some interfaces are functional incidentally, it is not necessary or desirable that all declarations of functional interfaces be annotated with @FunctionalInterface.

Of course you could use it in a lambda by relying on a external Foo instance and not this as we generally do in compareTo() implementation :

Foo one = new Foo(...);
Comparable<Foo> comparableForOne = other -> one.getX().compareTo(other.getX()));

Foo anotherFoo = new Foo(...);
int result = comparableForOne.compareTo(anotherFoo);

But that would be undesirable since a misuse of the Comparable interface that is designed to work for any instance of the class and not a specific instance.

like image 35
davidxxx Avatar answered Dec 28 '22 03:12

davidxxx