Search code examples
scalaprimitiveprimitive-types

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


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?


Solution

  • 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.