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

1

5

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?

Interregnum answered 28/6, 2019 at 13:29 Comment(0)
S
6

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

Storz answered 28/6, 2019 at 13:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.