https://kotlinlang.org logo
#announcements
Title
# announcements
b

bbaldino

08/02/2019, 3:35 PM
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

Ruckus

08/02/2019, 3:40 PM
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

bbaldino

08/02/2019, 3:40 PM
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

Ruckus

08/02/2019, 3:48 PM
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

bbaldino

08/02/2019, 3:48 PM
cool, will file something
r

Ruckus

08/02/2019, 3:50 PM
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

bbaldino

08/02/2019, 3:51 PM
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

Ruckus

08/02/2019, 4:52 PM
Looks like it. That's interesting.
2 Views