1. Overview
In this tutorial, we’ll learn how to reverse the sign of an Int in Scala using the standard library.
2. Multiplying by -1
Reversing the sign of an Int in Scala is a simple operation.
The first approach is simply multiplying the number by -1:
scala> val x = 3
x: Int = 3
scala> x * -1
res0: Int = -3
3. Using the Compound Assignment Operator
If we’re using variables instead, we can also use the compound assignment operator to assign the new value:
scala> var y = 7
y: Int = 7
scala> y *= -1
scala> y
res2: Int = -7
4. Using the Unary Minus Operator
A similar approach would be to use the unary minus operator:
scala> -x
res0: Int = -3
scala> -y
res1: Int = 7
5. Subtracting From Zero
Another possible approach is to subtract the value from 0:
scala> x
res3: Int = 3
scala> 0 - x
res4: Int = -3
scala> y
res5: Int = -7
scala> 0 - y
res6: Int = 7
6. Using Two’s Complement
There are other approaches that, while correct, are unnecessarily more complex. For instance, we could use Two’s complement, which negates all bits, and then, we just need to add one to the result:
scala> val a = 4
a: Int = 4
scala> ~a
res0: Int = -5
scala> ~a + 1
res1: Int = -4
scala> val b = -6
b: Int = -6
scala> ~b + 1
res2: Int = 6
7. Using Java’s Math.negateExact Method
Finally, we can make use of the Java standard library’s Math.negateExact() method:
scala> Math.negateExact(a)
res3: Int = -4
scala> Math.negateExact(b)
res4: Int = 6
This method can be useful if we’re applying a lambda, allowing us to pass just the method reference instead of all the boilerplate for the anonymous function:
scala> val lst = List(1,2,3)
lst: List[Int] = List(1, 2, 3)
scala> lst.map(elem => elem * -1)
res0: List[Int] = List(-1, -2, -3)
scala> lst.map(Math.negateExact)
res1: List[Int] = List(-1, -2, -3)
8. The Integer.MIN_VALUE Edge Case
While we saw many different solutions, none of them will work with the Integer.MIN_VALUE:
scala> Integer.MIN_VALUE
res0: Int = -2147483648
scala> Integer.MIN_VALUE * -1
res1: Int = -2147483648
scala> Math.negateExact(Integer.MIN_VALUE)
java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.negateExact(Math.java:1335)
... 26 elided
This happens due to the way Ints are represented, which limits the max value to 231-1, and the min value to -231. So, we can either add a check for this edge case or use the Math.negateExact() method that will throw an exception for us.
9. Conclusion
In this article, we’ve learned how to easily reverse the sign of an Int in Scala using the standard library. We started by looking at the most trivial approaches with the arithmetic operation of multiplying by -1, and then we moved to use the two’s complement and the Java Math.negateExact() method.
We also checked the Integer.MIN_VALUE edge case, which will not work properly for the approaches seen.
Also, note that all approaches except two’s complement will work for non-integers as well, such as Float and Double.