gpt4 book ai didi

scala - Scala 上的运算符短返回 Int?

转载 作者:行者123 更新时间:2023-12-04 09:32:04 25 4
gpt4 key购买 nike

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

count :Short
count += 1.toShort

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

我需要简短,因为我将结果存储在数据库中并希望节省磁盘空间。我当然可以让计算发生在 Int然后总是调用 .toShort存储之前的结果,但这有点违反直觉。

最佳答案

这几乎可以肯定是因为 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 todouble.
  • Otherwise, if either operand is of type float, the other isconverted to float.
  • Otherwise, if either operand is of type long, theother is converted to long.
  • Otherwise, both operands are converted totype 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 提供的选项的最简单、最有效的方式。

关于scala - Scala 上的运算符短返回 Int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32277626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com