Does the Kotlin standard library offer a version o...
# getting-started
k
Does the Kotlin standard library offer a version of the modulus/remainder function that guarantees a non-negative result? I only see a version that preserves the sign of the left operand and a version that preserves the sign of the right operand.
a
I do my best to understand your question, but I fail. Any code snippet to show your expectation?
s
I think what @Kelvin Chung is taling about is that
-5%2
evaluates to
-1
and not
1
.
In which case the mod function is your friend:
(-5).mod(2) -> 1
k
@Stephan Schröder I don't think so, since "I only see a version that preserves the sign of the left operand" is
rem
(
%
) and "a version that preserves the sign of the right operand" is
mod
. Neither
rem
nor
mod
meets the stated requirement that it "guarantees a non-negative result". Having said that, I cannot think of any valid use case for such a requirement.
s
@Klitos Kyriacou I can't even think about a usecase where the right operand is negative, that being said, I think this would be the extension function to have the desired behaviour:
Copy code
fun Int.posRemainder(other:Int): Int = (this%other).let { rem->
    if(rem>=0) {
        rem
    } else {
        rem + kotlin.math.abs(other)
    }
}
g
Why not
Copy code
fun Int.posRemainder(other:Int): Int = this.mod(abs(other))
then?
k
For the record, Java's
BigInteger
has it that
rem
acts like
%
(preserves the sign of the left operand) and
mod
guarantees a non-negative result; they don't have an operation that preserves the sign of the right operand. Which is very confusing.
k
@Kelvin Chung It does preserve the sign of the right operand, but the right operand must be positive, and therefore the result also happens to be always positive.