以下(逻辑上)是编译时错误:
public int myMethod(MyObject input) {
if (input == null) {
return null; // compiler says I cannot return null for primitive type
} else {
return 1;
}
}
到目前为止,一切都很好。我不明白的是,以下内容是允许的:
public int myMethod(MyObject input) {
return input == null ? null : 1;
}
为什么?对于编译器来说认识到这一点应该很简单,还是我在这里错过了一些关键点?
(当然,如果在三元运算符中最终出现在“空分支”上,那么它就是一个 NPE,还有什么?:))
三元条件运算符的类型由其第二个和第三个操作数的类型决定。
如果是
input == null ? null : 1
类型是Integer
,可以同时分配null
and 1
.
编译器允许你的方法返回一个Integer
因为它可以自动拆箱成int
,所以它适合int
返回类型为myMethod
.
事实上,您的特定代码可能会抛出NullPointerException
不是编译器可以检测到的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)