would_like_to_be_anon
would_like_to_be_anon

Reputation: 1727

How does this lambda feature in java 8 work?

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.

Upvotes: 7

Views: 193

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280178

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.

Upvotes: 14

Related Questions