Scala 上的运算符 short return Int?

Operators on Scala short return Int?

我是 Scala 的新手,我很好奇为什么 ++= 运算符 return 是 Int 而不是 Short?我有一个简单的 代码如下,

count :Short
count += 1.toShort

但是 += 运算符 return 是 Int,我假设这是故意的,想知道原因。

我需要这个很短,因为我将结果存储在数据库中并想将 space 保存在磁盘上。我当然可以让计算发生在 Int 中,然后在存储之前总是对结果调用 .toShort 但这有点违反直觉。

阿图尔,问得好。这是我的想法- 当我查看 ScalaDoc for "Short" 时,运算符 += 不存在。我猜这意味着编译器会帮助你一点并将它翻译成 count = 1.toShort + count。现在 + 运算符总是 returns 和 Int。 这有意义吗?

我回答后问题变了。我的回答现在只针对第一部分。

希望仍然有帮助。

这几乎可以肯定,因为在 Java 和 JVM 字节码中就是这样处理的。扩大到 integer 的提升与 Java 中的处理方式一致,并且无需执行任何额外的转换操作。来自 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.

强调我的。 Java(语言)这样做的原因是 JVM 规范的编写方式。来自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.

再次强调我的。所以 Scala 这样做是因为它是使用 JVM 提供的选项的最简单、最有效的方法。