Lionel Lionel - 1 year ago 119
Scala Question

Scala bit operation

I'm doing some research on scala bit operation as below:

scala> val b = 8
b: Int = 8

scala> var c:Int = b | (1<<4)
c: Int = 24

scala> var c:Int = c | (1<<5)
c: Int = 32

I don't understand why the result looks correct when assign value from b to c but looks incorrect when from c to itself. The expect result is 56 for the 3rd statement. Anybody knows why?

Answer Source

In the third line, you are redefining variable c. The REPL apparently works in such a way that it first creates the variable which is set to its default value 0 and then it does 0 | (1 << 5) which is 32.

Solution: Don't redefine the variable c, just reassign it:

scala> val b = 8
b: Int = 8

scala> var c: Int = b | (1 << 4)
c: Int = 24

scala> c = c | (1 << 5)      // Don't redefine c, just reassign it
c: Int = 56

In a "real" program (not in the REPL) you cannot define the same variable with the same name more than once in the same scope. You'd get a compiler error if you would try to redefine the variable c.