Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method returning a lambda depend on the return type of the interface method?

I am looking at existing code and trying to understand how lambda expressions and functional interfaces work.

Here is the code:

public interface MyComparator<T> {
    public int compare(T t1, T t2);

    public static MyComparator<Person> comparing(Function<Person, Comparable> fun) {
        return (p1, p2) -> fun.apply(p1).compareTo(fun.apply(p2));
    }
}

The above piece of code compiles properly without any issues, but if I change the return type of the compare method from int to String, I get an error:

Type mismatch: cannot convert from int to String

    public int compare(T t1, T t2);

Why is the comparing method dependent on the compare method?

like image 343
pin Avatar asked Jun 16 '26 01:06

pin


1 Answers

Your function type is Function<Person, Comparable>, which means fun.apply(p1) returns a Comparable. This is an interface defined in the Java standard library, which declares a method named compareTo which returns an int, so therefore your lambda returns an int.

This means if you define your functional interface as having a single abstract method returning an int, then your lambda conforms to the functional interface because it does return int. But if you define that abstract method as returning a String, then the lambda does not conform to the functional interface, because it does not return a String.

In the latter case, it is a type error for your comparing method to return that lambda, since the signature of comparing says it should return an instance implementing your functional interface, but the lambda does not conform to that functional interface due to the lambda having the wrong return type.

like image 188
kaya3 Avatar answered Jun 18 '26 16:06

kaya3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!