The absolute value of a hash code or random integer is taken, which is negative for the minimum value

tx0/kotlin:abs-can-be-negativerecommendedwarningreliability/arithmeticdepth fastbug

What it finds

abs(key.hashCode()) % buckets assumes a non-negative result, but abs(Int.MIN_VALUE) is Int.MIN_VALUE, which stays negative, so one hash in four billion gives a negative index. Math.floorMod, mod, or masking with and Int.MAX_VALUE gives a non-negative value.

Reported for abs, Math.abs and absoluteValue applied to hashCode(), and to nextInt() or nextLong() without bounds.

From the rule's source, abs_of_random.rs.

Example from the rule's tests
import kotlin.math.absimport kotlin.random.Random fun bucket(key: Any, buckets: Int, random: java.util.Random): Int {    val a = abs(key.hashCode()) % bucketstx0 reports: abs(key.hashCode()) is negative    val b = Math.abs(random.nextInt()) % bucketstx0 reports: abs(random.nextInt()) is negative    val c = key.hashCode().absoluteValue % bucketstx0 reports: key.hashCode().absoluteValue is negative    val d = abs(random.nextInt(10))    val e = Random.nextInt().mod(buckets)    return a + b + c + d + e}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:abs-can-be-negative" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:abs-can-be-negative] reason="..."

tx0 explain tx0/kotlin:abs-can-be-negative shows the same in the terminal. Found a false positive? Report it.