leftShift method on BigInteger in Groovy

How to perform a leftShift operation on a BigInteger in Groovy?

The leftShift method is defined in Groovy’s JDK enhancement

However, the below code throws an UnsupportedOperationException exception:

Integer i = new Integer(3)
println(i << 2)

BigInteger b = new BigInteger("3")
println(b << 2)

Result:

12   <-- working for Integer
Caught: java.lang.UnsupportedOperationException: Cannot use leftShift() on this number type: java.math.BigInteger with value: 3
java.lang.UnsupportedOperationException: Cannot use leftShift() on this number type: java.math.BigInteger with value: 3
        at test.run(test.groovy:5)

I suppose I could use the BigInteger.shiftLeft() method (note it’s not leftShift but shiftLeft…), but in the end, I would like to use the << operator on a Number, which could be either an Integer or a BigInteger.

Bug in Groovy? (I’m using 3.0.4)

Answer

For whatever reason the underlying BigIntegerMath does not override the leftShiftImpl() method, which results in an UnsopportedOperationException.

Might be worth to file an issue.

For now you have to resort to workarounds like

assert 12 == new BigInteger(3).intValue() << 2
//or
assert 12 == new BigInteger(3).shiftLeft( 2 )

Leave a Reply

Your email address will not be published. Required fields are marked *