is there a trick to implementing preincrement for ...
# announcements
b
is there a trick to implementing preincrement for an inline class wrapping an int? post-increment is working fine for me but preincrement isn't
r
Can you provide an example of your issue? You don't implement pre vs post, you just implement
inc
and whether it's pre or post depends on how you use it.
b
yeah that's what i thought, but i get different behaviors for each. let me see if i can slim down an example
Copy code
inline class WrappingInt(val value: Int) {
    operator fun inc(): WrappingInt = plus(1)
    operator fun plus(num: Int): WrappingInt = WrappingInt((value + num) and 0xFFFF)
}

fun main() {
    var x = WrappingInt(65535)
    x++
    println(x) // prints 0 (correct)

    var y = WrappingInt(65535)
    ++y
    println(y) // prints 65536
}
🤔 1
r
Interesting, and removing the
inline
fixes it. I think you've found a bug. You should report it at kotl.in/issue (and link it back here)
b
cool, will file something
r
Ah, it looks like the prefix is being compiled directly to
IINC
whereas the postfix is correctly compiled to
INVOKESTATIC WrappingInt.inc-impl
. Good catch.
b
ah yeah, see that now
something like this does seem to work:
Copy code
var z = WrappingInt(65535)
    val zz = { ->
        ++z
        println(z)
    }
i guess it's triggering some boxing maybe?
i had unit tests for pre-increment and they actually work inside a kotlintest
should
block for this reason, i think, so this was a sneaky one 😕
r
Looks like it. That's interesting.