Is there an easy/already existing way to replace a...
# getting-started
k
Is there an easy/already existing way to replace all integer additions, subtractions and multiplications to strict math variants in kotlin code?
j
What are strict math variants of integer operations?
k
I'm currently considering something that just transforms all class files with asm
Strict math throws when there is overflow
This is for advent of code mostly, cause I've had a few times the issue that ints where too small for my calculations and getting an error instead of having to debug for a long time would be very helpful
c
Instead of mucking around with the AST or bytecode, you might just use BigInteger and BigDecimal instead of Int/Double if you suspect the values might overflow. The stdlib has operators defined on both these types, so they’re nearly as easy to use as the primitive equivalents
l
Do the overloads set a limit on the size of BigDecimal operations? It always was annoying to see BigDecimal(1.0).divide(BigDecimal(10.0) fail since it would try to exactly represent 0.1 in binary. Always had to make sure to set the precision of the operation.
e
I've already implemented a classfile transformer that converts primitive numeric operations to their strict counterparts: https://github.com/ephemient/kotlin-numeric
but Advent of Code is designed to work on all (modern) language, including those without floating point numbers and those with only floating point numbers, so no problem ever required integers larger than 2^53
as long as you pick the right approach,
Long
will be good enough
k
yes, but I had a problem where I used 2 longs and I wanted to check if they had the same sign, so I multiplied them, which overflowed
ended up fixing it by using .sign(), but if it had crashed instead I wouldn't had to debug as long