I've been working a bit lately on implementing a binary network protocol in Scala. Many of the fields in the packets map naturally to Scala Shorts. I would like to concisely increment a Short
variable (not a value). Ideally, I would like something like s += 1
(which works for 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
The +=
operator is not defined on Short
, so there appears to be an implicit converting s
to an Int
preceding the addition. Furthermore Short
's + operator returns an Int
.
Here's how it works for Ints:
scala> var i = 0
i: Int = 0
scala> i += 1
scala> i
res2: Int = 1
For now I'll go with s = (s + 1).toShort
Any ideas?
shorts
. The bytecode instructions always operate onint
s. See the Java Virtual Machine Specification. – Ferrate