Java在三元数中为基本类型返回null [英] Java return null for primitive in ternary
问题描述
以下(逻辑上)是编译时错误:
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?
(当然,如果在三元运算符中,结果以 null-分支,那么它是一个NPE,还有什么?:))
(And of course if in the ternary operator one ends up on the "null-branch", then it's a NPE, what else? :))
推荐答案
三元条件运算符的类型由第二和第三操作数的类型。
The type of the ternary conditional operator is determined by the types of its 2nd and 3rd operands.
对于
input == null ? null : 1
类型为 Integer
,可以同时分配 null
和 1
。
the type is Integer
, which can be assigned both null
and 1
.
编译器允许您的方法返回 Integer
,因为它可以自动拆箱为 int
,因此适合 int
返回类型为 myMethod
。
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
.
编译器无法检测到您的特定代码可能引发 NullPointerException
的事实。
The fact that your specific code may throw a NullPointerException
is not something the compiler can detect.
这篇关于Java在三元数中为基本类型返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!