在 Scala 中递增 Short 类型变量最简洁的方法是什么?

What is the most concise way to increment a variable of type Short in Scala?

我最近一直在研究如何在 Scala 中实现二进制网络协议。数据包中的许多字段自然映射到 Scala Shorts。我想简洁地增加一个 Short 变量(不是一个值)。理想情况下,我想要 s += 1 之类的东西(适用于 Ints)。

scala> var s = 0:Short
s: Short = 0

scala> s += 1
<console>:9: error: type mismatch;
 found   : Int
 required: Short
              s += 1
                ^

scala> s = s + 1
<console>:8: error: type mismatch;
 found   : Int
 required: Short
       s = s + 1
             ^

scala> s = (s + 1).toShort
s: Short = 1

scala> s = (s + 1.toShort)
<console>:8: error: type mismatch;
 found   : Int
 required: Short
       s = (s + 1.toShort)
              ^

scala> s = (s + 1.toShort).toShort
s: Short = 2

+= 运算符未在 Short 上定义,因此似乎在加法之前将 s 隐式转换为 Int。此外 Short 的 + 运算符 returns 和 Int。 这是它对 Ints 的工作方式:

scala> var i = 0
i: Int = 0

scala> i += 1

scala> i
res2: Int = 1

现在我会选择 s = (s + 1).toShort

有什么想法吗?

您可以定义一个隐式方法,将 Int 转换为 Short:

scala> var s: Short = 0
s: Short = 0

scala> implicit def toShort(x: Int): Short = x.toShort
toShort: (x: Int)Short

scala> s = s + 1
s: Short = 1

编译器将使用它来匹配类型。请注意,虽然隐式也有不足之处,但在某些地方您可能会在不知道为什么的情况下发生转换,仅仅因为该方法是在作用域中导入的,代码的可读性也会受到影响。