Java return null for primitive in ternary [duplicate]

≡放荡痞女 提交于 2019-12-19 09:24:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!