Search code examples
clojureinteger-overflow

Clojure, I want Long multiplication to overflow


I want to do 64 bit arithmetics (not natural numbers), so I e.g. need a multiplication of two longs to overflow silently.

(unchecked-multiply Long/MAX_VALUE 3)

does the trick. But

(def n Long/MAX_VALUE)
(unchecked-multiply n 3)

gives an overflow exception. What am I doing wrong?

(Clojure 1.5.1)


Solution

  • In the first case, both arguments are unboxed longs, so the (long, long) overload of clojure.lang.Numbers.unchecked_multiply is used. As expected, it does not throw on overflow.

    In the second case, n is boxed, so the (Object, Object) overload is called, and that simply delegates to the multiply method which throws on overflow.

    You need to say

    (unchecked-multiply (long n) 3)
    

    so that the (long, long) overload is used.