I don’t understand why Short + Short is giving an ...
# announcements
p
I don’t understand why Short + Short is giving an Int
d
I don't know why but it might be because the numeric operator APIs in Kotlin sort-of follows the numeric promotion rules that JSL defines? 🤷‍♂️ https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.6.2 Maybe someone else can shed some light on the topic.
o
Short (at least on the JVM) can go up to 32,767. If you add two values that can go up to 32,767, you get a maximum value of 65,534, which can’t be stored in a Short
t
Binary numeric operations that don't use double, float or long will always be converted to int for the calculation. I'm no expert on the deep inner workings of this, but I guess this is due to how the machine code works and the binary commands probably need an int-sized number. Now, if the calculation happens as an int, it makes sense to also return that and not artificially limit the result to something smaller. If you need a short as your result, you will have to manually convert it back.
@outadoc I don't see that as an argument. You could also add two ints and get a value that doesn't fit, but that operation doesn't return a long.
o
True, your explanation makes more sense 🙂
j
The JVM operand stack is specified as having 32-bit units, where a long/double takes up two units and everything else takes up 1. Not sure why that is offhand, but I guess it follows @Tobias Berger’s argument from there. Old JVM spec but pretty sure it still applies! https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.6.2
e
yes, there are no boolean/byte/short/char types in JVM's frames' local variables and operand stacks, they're all represented by int
like Java and C, Kotlin's arithmetic promotes narrower types up to int
a
Because there is no JVM Bytecode that does addition of Short. And Short by default uses 4 bytes similar to Int unless they are in a ShortArray.