Lionel
Lionel

Reputation: 13

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?

Upvotes: 1

Views: 618

Answers (2)

Kevin Holditch
Kevin Holditch

Reputation: 5303

Because you are using the repl you are redinfing the variable c. So on the line

var c:Int = c | (1<<5)

It is the equivilant of

var c:Int = 0 | (1<<5)

Which is 32. If you use a new variable like d then you get 56 as you would expect.

Upvotes: 0

Jesper
Jesper

Reputation: 206816

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.

Upvotes: 2

Related Questions