Scala按位运算

Dim*_*tri 2 scala bit-manipulation

我正在定义一个简单的函数来执行一些按位操作:

def getBit(num:Int, i:Int):Boolean = (num & (1 << i) != 0)
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

    <console>:7: error: overloaded method value & with alternatives:
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Boolean)
       def getBit(num:Int, i:Int):Boolean = (num & (1 << i) != 0)
Run Code Online (Sandbox Code Playgroud)

为什么我不能使用&运营商?我该如何解决这个错误?

LuG*_*uGo 6

以下代码应该有效: def getBit(num:Int, i:Int):Boolean = ((num & (1 << i)) != 0)


Ed *_*aub 5

运算符 & 与 && 具有相同的优先级,而 | 具有与 || 相同的优先级,因此您的表达式的计算顺序与您预期的不同。请参阅Scala 规范的第 6.12.3 节。

& 和 | 的优先级 是非直观的低,并且是错误的常见来源。一个好的工作习惯是总是在它们周围加上括号。