3

I came to code:

 scala> val a = 0 | 1
 a: Int = 1
 scala> val a = 0 | 1 | 2
 a: Int = 3
 scala> val a = 0 | 1 | 2 | 3
 a: Int = 3
 scala> val a = 0 | 1 | 2 | 3 | 4
 a: Int = 7

The only result I expected from the | operator is the result of the first command. I see it behaves like a logic or and also it adds elements in the second command.

Could someone explain the working of the | operator using integers as operators?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
Evhz
  • 8,852
  • 9
  • 51
  • 69

2 Answers2

5

It's just a logical or between each bit of binary representation of integer value (1 or 1 = 1, 1 or 0 = 1, 0 or 1 = 1, 0 or 0 = 0)

val a = 0 | 1 
//0 or 1 = 1 (1 - decimal number)

val a = 0 | 1 | 2
//00 or 01 or 10 = 11 (3 - decimal number)

val a = 0 | 1 | 2 | 3
//00 or 01 or 10 or 11 = 11 (3 - decimal number)

val a = 0 | 1 | 2 | 3 | 4
//000 or 001 or 010 or 011 or 100 = 111 (7 - decimal number)
Bogdan Vakulenko
  • 3,380
  • 1
  • 10
  • 25
5

| is the bitwise OR operator:

val a = 0 | 1
a: Int = 1

00  0
01  1
-----
01  1
val a = 0 | 1 | 2 | 3
a: Int = 3

00  0
01  1
10  2
11  3
------
11  3

val a = 0 | 1 | 2 | 3 | 4
a: Int = 7

000  0
001  1
010  2
011  3
100  4
-------
111  7
Mario Galic
  • 47,285
  • 6
  • 56
  • 98