The JLS casting rules seem rather complicated in this question: is it correct to refer to a method that returns a certain value, to a link that accepts the same types of arguments but returns void? I think this is normal, because voidnarrower than any type.
For instance...
import java.util.function.Consumer;
public class MethodRefCaster {
Integer fooOp(Integer x) {
System.out.println(x);
return x + 3;
}
void applyOpToBar(Consumer<Integer> op, int bar) {
op.accept(bar);
}
public static void main(String [] args) {
MethodRefCaster x = new MethodRefCaster();
x.applyOpToBar((Consumer<Integer>) x::fooOp, 42);
}
}
This prints 42, as you might expect. But is Java correct? Many thanks.
source
share