There are a bunch of questions where people have realized that creating a method reference with an expression that evaluates to a null
value will result in a NullPointerException
. As an example:
String s = null;
Supplier<char[]> fun = s::toCharArray;
This is due to the following paragraph in the java specification:
First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference expression completes abruptly. If the subexpression completes abruptly, the method reference expression completes abruptly for the same reason.
Now my question is, does anyone happen to know what the reason behind this (based on the many confused questions) counterintuitive specification was/is?
The only thing that comes to my mind is that in the following case it is hard to accurately report the error of the NullPointerException
if it happens during the evaluation of the Supplier
:
public static char[] callback(Supplier<char[]> supplier) {
return supplier.get();
}
public static void main(String[] args) {
String s = null;
callback(s::toCharArray);
}