I have a question regarding Java 8 inference with respect to lambdas and their related exception signatures.
If I define some method foo:
public static <T> void foo(Supplier<T> supplier) {
//some logic
...
}
then I get the nice and concise semantic of being able to write foo(() -> getTheT());
in most cases for a given T
. However, in this example, if my getTheT
operation declares that it throws Exception
, my foo
method which takes a Supplier no longer compiles: the Supplier method signature for get
doesn't throw exceptions.
It seems like a decent way to get around this would be to overload foo to accept either option, with the overloaded definition being:
public static <T> void foo(ThrowingSupplier<T> supplier) {
//same logic as other one
...
}
where ThrowingSupplier is defined as
public interface ThrowingSupplier<T> {
public T get() throws Exception;
}
In this way, we have one Supplier type which throws exceptions and one which doesn't. The desired syntax would be something like this:
foo(() -> operationWhichDoesntThrow()); //Doesn't throw, handled by Supplier
foo(() -> operationWhichThrows()); //Does throw, handled by ThrowingSupplier
However, this causes issues due to the lambda type being ambiguous (presumably unable to resolve between Supplier and ThrowingSupplier). Doing an explicit cast a la foo((ThrowingSupplier)(() -> operationWhichThrows()));
would work, but it gets rid of most of the conciseness of the desired syntax.
I guess the underlying question is: if the Java compiler is able to resolve the fact that one of my lambdas is incompatible due to it throwing an exception in the Supplier-only case, why isn't it able to use that same information to derive the type of the lambda in the secondary, type-inference case?
Any information or resources which anyone could point me to would likewise be much appreciated, as I'm just not too sure where to look for more information on the matter.
Thanks!
question from:
https://stackoverflow.com/questions/32323081/why-doesnt-java-8-type-inference-consider-exceptions-thrown-by-lambdas-in-overl 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…