In Kotlin, why is (-1 ushr 4) different from -1.ushr(4)?

4

In both Kotlin REPL and Kotlin/JVM:

  • -1 ushr 4 evaluates to 268435455
  • -1.ushr(4) evaluates to 0

The first one is correct, as -1 is 0xFFFFFFFF, so 0x0FFFFFFF is 268435455, but what makes the second different?

kotlin
bitwise-operators
infix-operator
asked on Stack Overflow Jun 28, 2019 by Alexander Hausmann • edited Jun 28, 2019 by Alexander Hausmann

1 Answer

7

That depends on operator priority. In the first case, the operation is resolved as (-1) ushr 4, while in the second case it's -(1 ushr 4).

This happens because (quoting the documentation):

Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator. The following expressions are equivalent:

1 shl 2 + 3 and 1 shl (2 + 3)

While method call has a higher priority than -.

answered on Stack Overflow Jun 28, 2019 by user2340612 • edited Jun 28, 2019 by user2340612

User contributions licensed under CC BY-SA 3.0