Why does functional interface with void return-type method accept any return-type method?

Yevhenii Smyrnov :

We have this code:

public class Test {
    public static Object foo() {
        System.out.println("Foo");
        return new Object();
    }

    public static void main(String[] args) {
        J j = Test::foo;
        j.m();
    }

}
interface J {
    void m();
}

And this code will work. The crucial line is

J j = Test::foo;

Although interface J declares it has a void function, Test::foo returns an Object.

While we can't override method while implementing interface (which is obvious). This works only when interface's method is void, otherwise the code won't be compiled. Could someone tell why does this work in the way it works? :D

Andrew Tobilko :

Although interface J declares it has a void function, Test::foo returns an Object.

It's inaccurate to say that Test::foo returns something. In different contexts, it could mean different things.

Supplier<Object>  a = Test::foo;
J                 b = Test::foo;
Runnable          c = Test::foo;

It's more accurate to say that Test::foo can represent a target type the functional method of which returns either void or Object.

It's an example of expression statement (jls-14.8).

If the target type's function type has a void return, then the lambda body is either a statement expression (§14.8) or a void-compatible block (§15.27.2).
...
An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306801&siteId=1