When checking whether a number is odd, always use
x % 2 != 0
rather than the more commonx % 2 == 1
.
Note that, unlike most rules here, this one is not Scala specific.
There are odd numbers whose division by 2 has a remainder that’s not 1:
-3 % 2
// res0: Int = -1
The mathematical definition of odd and even numbers is:
This suggests the following implementations:
def isEven(i: Int): Boolean = i % 2 == 0
def isOdd(i: Int): Boolean = i % 2 != 0
And, indeed:
-3 % 2 != 0
// res1: Boolean = true
Linter | Rule |
---|---|
Scapegoat |
|