Reputation: 135
I am new to Scala and I am curious why do +
or +=
operators return a Int
instead of a Short
? I had a simple
code as follows,
count :Short
count += 1.toShort
but the +=
operator returns an Int
, I am assuming this is deliberate and want to know the reason.
I need this to be short because I am storing the result in a DB and would like to save space on the disk. I could of course let the calculations happen in Int
and then always call .toShort
on the result before storing but this is a bit counter intuitive.
Upvotes: 4
Views: 2262
Reputation: 10623
This is almost certainly because that's how it's handled in Java and JVM Bytecode. Having widening promotion to integer
is consistent with how it's handled in Java, and removes the need to do any additional casting operations. From the Java language specification
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
emphasis mine. The reason Java (the language) does it this way is because of how the JVM specification is written. From the Java Virtual Machine Specification,
Note that most instructions in Table 2.2 do not have forms for the integral types byte, char, and short. None have forms for the boolean type. A compiler encodes loads of literal values of types byte and short using Java Virtual Machine instructions that sign-extend those values to values of type int at compile-time or run-time. Loads of literal values of types boolean and char are encoded using instructions that zero-extend the literal to a value of type int at compile-time or run-time. Likewise, loads from arrays of values of type boolean, byte, short, and char are encoded using Java Virtual Machine instructions that sign-extend or zero-extend the values to values of type int. Thus, most operations on values of actual types boolean, byte, char, and short are correctly performed by instructions operating on values of computational type int.
Emphasis again mine. So Scala does this because its the easiest, most efficient way to work with the options given by the JVM.
Upvotes: 5
Reputation: 1042
Atul, Good question. Here are my thoughts -
When I looked at ScalaDoc for "Short", the operator +=
was not there. I am guessing this means the compiler helps you a bit and translates it to count = 1.toShort + count
. Now the +
operator always returns an Int
.
Does that make sense?
The question changed after I answered it. My answer now only addresses the first part.
Hope that still helps.
Upvotes: 0