7

I am trying to use java 8 features. While reading official tutorial I came across this code

static void invoke(Runnable r) {
    r.run();
}

static <T> T invoke(Callable<T> c) throws Exception {
    return c.call();
}

and there was a question:

Which method will be invoked in the following statement?"

String s = invoke(() -> "done");

and answer to it was

The method invoke(Callable<T>) will be invoked because that method returns a value; the method invoke(Runnable) does not. In this case, the type of the lambda expression () -> "done" is Callable<T>.

As I understand since invoke is expected to return a String, it calls Callable's invoke. But, not sure how exactly it works.

0

1 Answer 1

14

Let's take a look at the lambda

invoke(() -> "done");

The fact that you only have

"done"

makes the lambda value compatible. The body of the lambda, which doesn't appear to be an executable statement, implicitly becomes

{ return "done";} 

Now, since Runnable#run() doesn't have a return value and Callable#call() does, the latter will be chosen.

Say you had written

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

instead, the lambda would be resolved to an instance of type Runnable, since there is no expression that could be used a return value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.