I have this piece of code
public <T> someMethod(Supplier<T> supplier) {
Objects.requireNonNull(supplier);
SupplierThrowsException<T, Throwable> supplierThrowsException = supplier::get;
return withThrowable(supplierThrowsException);
}
I am calling it like this
obj.someMethod(() -> myMethod(message))
I am 100% sure that the class of the object returned by myMethod()
does not implement Supplier interface. So where is the implementation of get()
.
I went through the Javadoc, I didn't get anything. I would like to understand what's going on here.
I found this and this but it doesn't clear my doubt. Let me know if I am missing anything here.
I am 100% sure that the class of the object returned by
myMethod()
does not implementSupplier
interface.
Sure, but the expression () -> myMethod(message)
does.
Please, read 15.27.4. Run-Time Evaluation of Lambda Expressions.
At run time, evaluation of a lambda expression is similar to evaluation of a class instance creation expression, insofar as normal completion produces a reference to an object. Evaluation of a lambda expression is distinct from execution of the lambda body.
Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.
The value of a lambda expression is a reference to an instance of a class with the following properties:
- The class implements the targeted functional interface type and, if the target type is an intersection type, every other interface type mentioned in the intersection.
In short, the lambda expression () -> myMethod(message)
will be resolved to an instance of Supplier
.
Where is the implementation of
get
()?
You've provided it within the lambda body.
() -> myMethod(message)
(it's a statement expression, a shorter form to construct a lambda body)
() -> {
return myMethod();
}
(it's a value-compatible block, a more expanded version where many statements may be declared)