【问题标题】:What is the most concise way to increment a variable of type Short in Scala?在 Scala 中增加 Short 类型变量的最简洁方法是什么?
【发布时间】:2015-08-06 21:46:51
【问题描述】:

我最近一直致力于在 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 的 + 运算符返回一个 Int。 以下是 Ints 的工作原理:

scala> var i = 0
i: Int = 0

scala> i += 1

scala> i
res2: Int = 1

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

有什么想法吗?

【问题讨论】:

  • 有点晚了,我找到了一个[相关帖子] (stackoverflow.com/questions/10975245)。 Ende Neu 的回答,用 Paul 的扩展提供了一个更好的解决方案。链接的帖子确实在一定程度上说明了 Paul 的扩展工作的原因。
  • 另外值得注意的是,JVM 不直接支持shorts 上的算术运算。字节码指令总是在ints 上运行。请参阅Java Virtual Machine Specification

标签: scala primitive primitive-types


【解决方案1】:

您可以定义一个隐式方法,将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

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

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多