问题
The following (logically) is a compile-time error:
public int myMethod(MyObject input) {
if (input == null) {
return null; // compiler says I cannot return null for primitive type
} else {
return 1;
}
}
So far so good. What I don't understand, that the following is allowed:
public int myMethod(MyObject input) {
return input == null ? null : 1;
}
Why? Recognising this should be straightforward for the compiler, or do I miss some crucial point here?
(And of course if in the ternary operator one ends up on the "null-branch", then it's a NPE, what else? :))
回答1:
The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.
In the case of
input == null ? null : 1
the type is Integer
, which can be assigned both null
and 1
.
The compiler allows your method to return an Integer
since it can be auto-unboxed into an int
, so it fit the int
return type of myMethod
.
The fact that your specific code may throw a NullPointerException
is not something the compiler can detect.
来源:https://stackoverflow.com/questions/44493258/java-return-null-for-primitive-in-ternary