在一个利用字节数组操作的项目上,我试图写这样的东西:
boolean enabled = getEnabled();
byte enabledByte = enabled ? 0x01 : 0x00; // compile error
我面临的问题是,上面的代码无法编译。
Type mismatch: cannot convert from int to byte
但是,如果我将其扩展为以下内容,它可以正常工作:
boolean enabled = getEnabled();
byte enabledByte;
if (enabled) {
enabledByte = 0x01;
} else {
enabledByte = 0x00;
}
引导我回答问题
Why can I not use byte assignments in short if statements?
最佳答案
0x00
和 0x01
是 int
文字:它们是带有 int
的表达式类型。 int
通常不能分配给 byte
,但如果表达式是编译时常量,它可以,前提是值在字节
的范围。
对于条件,分配的值是编译时常量:
if (enabled) {
enabledByte = 0x01;
} else {
enabledByte = 0x00;
}
这些赋值完全独立于编译器的观点。将常量值赋值为 1 的语句有 1 条,将常量值赋值为 0 的语句有 1 条。
对于每条语句,编译器可以保证适合字节的范围,因此它会自动将分配的值缩小到字节。
但是,带条件运算符的赋值:
enabledByte = enabled ? 0x01 : 0x00;
rhs 表达式是int
类型,但不是 编译时常量,因为enabled
在编译时未知。这两个可能的值 是 编译时常量并不重要,并且都适合 byte
:非常量第一个操作数使其非常量。因此,无法自动缩小条件运算符表达式的结果。
对此最有效的解决方案是将第二个和第三个操作数转换为 byte
:
enabled ? (byte) 0x01 : (byte) 0x00
这比
(byte) (enabled ? 0x01 : 0x00)
因为后者会在运行时强制转换,每次计算表达式时,而前者不会:操作数在编译时已经是字节,因此不需要强制转换。
关于java - 类型不匹配 : cannot convert from int to byte using ternary operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890653/