kotlinbitwise-operatorsinfix-operator

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


In both Kotlin REPL and Kotlin/JVM:

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


Solution

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