Reputation: 4189
Why the result of the modulo operation a % b
has the same type than a
instead of the b
type?
The remainder after a division never is going to be higher than the divisor, so the type of the result will fit in the divisor's type. So in a % b
, the result is going to fit in the b
's type.
So if b
is an Int
, the result should be Int
as well. Why is it a Long
?
Example:
val a: Long = Long.MaxValue
val b: Int = 10
a % b
Result:
a: Long = 9223372036854775807
b: Int = 10
res0: Long = 7
In the res0
, I was expecting an Int
.
I asked the same in the Scala contributors forum to be able to follow a conversation.
Upvotes: 3
Views: 167
Reputation: 170815
As mentioned in comments, Scala follows Java here. And Java follows C. And C actually has a good reason for this! Namely:
it has separate signed and unsigned types;
result of a % b
has the same sign as a
(e.g. -10 % 3
is -1
). (This wasn't required in older C versions, but always allowed.)
So if -10
above is signed long
and 3
is unsigned int
, then the result can't be the same type as the divisor because it must be signed. It couldn't be signed int
either, because instead of 3
we could have something which fits into unsigned int
but not signed int
. Applying the same rules as for other arithmetical operators gives reasonable return type, so that's what C does.
Upvotes: 3
Reputation: 48420
Because it resolves to the following overloaded version of Long.%
def %(x: Int): Long
where we see the return type is Long
.
Upvotes: 1