我刚刚注意到的好奇心,而不是问题。
我不允许写
public boolean x() {
return null;
}
或者这个:
public boolean x() {
if (DEBUG) {
return true;
} else {
return null;
}
}
但我可以写
public boolean x() {
return DEBUG ? true : null;
}
这是为什么? (如果采用“else”分支,它似乎会抛出 NPE。)
作为jls状态:
The type of a conditional expression is determined as follows:
If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
这意味着 java 允许 null
,因为它可以用来生成 Boolean
的实例,它可以拆箱为 boolean
(阅读有关更多信息的 jls 中关于 boxing 的部分)。但是由于 Boolean
实例被初始化为 null
,对 booleanValue()
的调用将导致 NullPointerException
。