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 methodinvoke(Runnable)
does not. In this case, the type of the lambda expression() -> "done"
isCallable<T>
.
As I understand since invoke
is expected to return a String
, it calls Callable's invoke. But, not sure how exactly it works.
Introduction. Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
Whenever a java compiler translates a lambda expression into byte code, it copies the lambda's body into a private method or private static method inside of the class in which expression is defined.
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
Characteristics of Lambda Expression Optional Type Declaration − There is no need to declare the type of a parameter. The compiler inferences the same from the value of the parameter. Optional Parenthesis around Parameter − There is no need to declare a single parameter in parenthesis.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With