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

1

9

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?

Ferrate answered 6/8, 2015 at 21:46 Comment(2)
Somewhat belated, I've found a [related post] (stackoverflow.com/questions/10975245). Ende Neu's answer, with Paul's extension provide a better solution. The linked post does illuminate somewhat why Paul's extension works.Ferrate
Also interesting to note, is that the JVM doesn't directly support arithmetic operations on shorts. The bytecode instructions always operate on ints. See the Java Virtual Machine Specification.Ferrate
S
8

You could define an implicit method that will convert the Int to a 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

The compiler will use it to make the types match. Note though that implicits also have a shortfall, somewhere you could have a conversion happening without even knowing why, just because the method was imported in the scope, code readability suffers too.

Sandler answered 6/8, 2015 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.