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

kil*_*ilo 8 primitive scala primitive-types

我最近在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
Run Code Online (Sandbox Code Playgroud)

+=操作者没有定义Short,因此似乎是一个隐式转换s到一个Int加法之前.此外,Short's +运算符返回一个Int.以下是Ints的工作原理:

scala> var i = 0
i: Int = 0

scala> i += 1

scala> i
res2: Int = 1
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

End*_*Neu 7

您可以定义一个隐式方法,将其转换IntShort:

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
Run Code Online (Sandbox Code Playgroud)

编译器将使用它来使类型匹配.请注意,虽然implicits也存在缺陷,但在某些地方你可能会发生转换,甚至不知道原因,只是因为方法是在范围内导入的,代码可读性也会受到影响.

  • 这也使得`s + = 1`也起作用. (2认同)