Java return 三进制中的原语为 null
Java return null for primitive in ternary
以下(逻辑上)是编译时错误:
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;
}
为什么?认识到这一点对于编译器来说应该是直截了当的,还是我错过了一些关键点?
(当然,如果在三元运算符中,一个以 "null-branch" 结束,那么它就是 NPE,还有什么?:))
三元条件运算符的类型由其第二个和第三个操作数的类型决定。
在
的情况下
input == null ? null : 1
类型为Integer
,null
和1
均可赋值。
编译器允许你的方法 return 一个 Integer
因为它可以自动拆箱成 int
,所以它适合 int
return 类型 myMethod
。
您的特定代码可能抛出 NullPointerException
这一事实是编译器无法检测到的。
以下(逻辑上)是编译时错误:
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;
}
为什么?认识到这一点对于编译器来说应该是直截了当的,还是我错过了一些关键点?
(当然,如果在三元运算符中,一个以 "null-branch" 结束,那么它就是 NPE,还有什么?:))
三元条件运算符的类型由其第二个和第三个操作数的类型决定。
在
的情况下input == null ? null : 1
类型为Integer
,null
和1
均可赋值。
编译器允许你的方法 return 一个 Integer
因为它可以自动拆箱成 int
,所以它适合 int
return 类型 myMethod
。
您的特定代码可能抛出 NullPointerException
这一事实是编译器无法检测到的。