如果在三元运算符中使用局部变量,为什么从 int 到 short 的缩小转换不起作用

Why does the narrowing conversion from int to short not work if local variable is used in the ternary operator

编译器 (sun-jdk-8u51) 接受了以下代码行,没有任何警告或错误:

short b = true ? 1 : 1;

而接下来的两行代码会导致编译错误(不兼容的类型:从 int 到 short 的可能有损转换):

boolean bool = true;
short s = bool ? 1 : 1;

为什么编译器无法在第二种情况下执行与原始整数 1 相同的 narrowing conversion

如@aioobe 在评论中所述:

This is because in the first case, since true is a compile time constant, the whole expression is evaluated during compile time, so you basically have short b = 1; whereas in the second version, the compiler does not do the simplification for you, hence the error

在变量bool的声明中加入final使其成为一个常量变量,这也允许编译器解释上述代码。

final boolean bool = true;
short s = bool ? 1 : 1;

section 4.12.4