I found a strange behaviour in the current version of Java 8. In my opinion the following code should be fine, but the JVM throws a NullPointerException
:
Supplier<Object> s = () -> false ? false : false ? false : null;
s.get(); // expected: null, actual: NullPointerException
It doesn't matter, what kind of lambda expression it is (same with java.util.function.Function
) or what generic types are used. There can also be more meaningful expressions in place of false ? :
. The example above is very short. Here's a more colorful example:
Function<String, Boolean> f = s -> s.equals("0") ? false : s.equals("1") ? true : null;
f.apply("0"); // false
f.apply("1"); // true
f.apply("2"); // expected: null, actual: NullPointerException
However these code pieces run fine:
Supplier<Object> s = () -> null;
s.get(); // null
and
Supplier<Object> s = () -> false ? false : null;
s.get(); // null
Or with function:
Function<String, Boolean> f = s -> {
if (s.equals("0")) return false;
else if (s.equals("1")) return true;
else return null;
};
f.apply("0"); // false
f.apply("1"); // true
f.apply("2"); // null
I tested with two Java versions:
~# java -version
openjdk version "1.8.0_66-internal" OpenJDK Runtime Environment (build 1.8.0_66-internal-b01) OpenJDK 64-Bit Server VM (build 25.66-b01, mixed mode)
C:\>java -version
java version "1.8.0_51" Java(TM) SE Runtime Environment (build 1.8.0_51-b16) Java HotSpot(TM) 64-Bit Server VM (build 25.51-b03, mixed mode)