涉及强制转换的奇怪编译错误

时间:2015-04-22 15:42:43

标签: java compiler-errors

在我的IDE中工作时,我发现了一些相当奇怪的东西。

double x1 = 0, x2 = 0;
int a = (int) x1 = (int) x2;

所以这是无效的语法,毫不奇怪。但是,为什么它的无效语法会让我感到困惑。当我将此代码放入Eclipse Luna并悬停在第二行时,会出现一条消息:

  

类型不匹配:无法从布尔值转换为int

     

提供1个快速修复:

     

更改' a'到布尔'

如果我忽略错误并继续运行,即使Throwable堆栈跟踪显示相同的消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
        Type mismatch: cannot convert from boolean to int
        Syntax error on token "=", <= expected

我不明白为什么编译器认为(int) x1 = (int) x2是某种评估为truefalse的比较。有没有人知道为什么会这样?

1 个答案:

答案 0 :(得分:3)

castoperator的优先级高于赋值运算符。因此,您无法将转换值分配给x1,因为编译器实际将其解释为:

...
cast x1 to integer
assign (int) x2 to the value of (int) x1
...

第2步不起作用,因为(int) x1不是lvalue(因为使用c ++中的术语,我不知道在java中是否存在同义词)。