Johan S
Johan S

Reputation: 3591

Scala bitwise operators on Bytes

I was trying to do some bitwise operators on bytes in Scala and I got some weird compilation-error:

scala> var a: Byte = 5 | 3
a: Byte = 7

scala> a |= 7
<console>:9: error: type mismatch;
 found   : Int
 required: Byte
              a |= 7
                ^

scala> a |= 7.toByte
<console>:9: error: type mismatch;
 found   : Int
 required: Byte
              a |= 7.toByte
                ^

So essentially I'm trying to create a var a: Byte = <something>, then when doing the bitwise-operators and equals to this re-assignable Byte it doesn't work, I have reported it as a bug but am I missing something? Is there a reason why this doesn't work?

Upvotes: 1

Views: 1407

Answers (1)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179119

That happens because the overloads of | are these:

def |(x: Byte): Int
def |(x: Char): Int
def |(x: Int): Int
def |(x: Long): Long
def |(x: Short): Int

As you can see, | returns either Int or Long, but no Byte, while your a variable has type Byte. Hence, it's unassignable.

Upvotes: 5

Related Questions