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

Viewed 120

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?

1 Answers

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 -.

Related