0

Is there a neat way to create an unsigned variable using scala value classes?

case class Size(val size: Int) extends AnyVal {
 ....
   }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
EY.Mohamed
  • 82
  • 6
  • 1
    https://github.com/scala/scala.github.com/pull/548 – sjrd Aug 30 '16 at 08:54
  • do you want something like this: `case class Size(size: Int) {def unsigned = if(size < 0) -size else size}; Size(-1).unsigned // 1` – Samar Aug 30 '16 at 08:54
  • I need it more in a way to have an error if size < 0 , i did it like this but i get the error : this statement is not allowed in value class. `case class Size(val size: Long) extends AnyVal { if (size < 0) throw new IllegalArgumentException; def +(s: Size): Size =Size(size + s.size) }` – EY.Mohamed Aug 30 '16 at 09:41
  • You are defining a "value class" and [value classes](http://docs.scala-lang.org/overviews/core/value-classes.html) don't allow any other operation except method definitions inside them. They also do not provide a constructor where you can validate the argument on instantiation. There are some work arounds: http://stackoverflow.com/questions/33136558/validations-in-value-classes – Samar Aug 30 '16 at 10:55

1 Answers1

0

These facts may help you understand you question. (For better explanation, assume all numbers are 4-bits, unsigned ranges from [0, 15], signed ranges from [-8, 7])

  1. In 2's complement, some number is same like -5 and 11 and 27 and so on, here the SAME not only means their representations are same, but also their operations:

    -5 + 10 = 5
    11 + 10 = 5
    
  2. What's the difference between (un)signed and 2's complement ? (un)signed number should handle overflow, bu 2's complement doesn't.

     7 + 1 = throw OverflowException
    -8 - 1 = throw OverflowException
    
  3. The number of jvm is neither signed nor unsigned, it's 2's complement. jvm does not throw any overflow when triggered, so they are 2's complement, not (un)signed numbers.

  4. What's the difference between signed and unsigned ?

    They overflow under different condition:

                 Signed           Unsigned
         7 + 1  overflow             8
     -8(7) - 1  underflow            6
         0 - 1     -1            underflow
    -1(15) + 1      0            overflow
    

    They are printed different.

These facts apply almost all programming languages.

Back to your question, since you don't handle overflow, the only thing you need to do is print it differently.

case class Size(val size: Int) extends AnyVal {
  override def toString = if (size < 0) ...
}
Zang MingJie
  • 5,164
  • 1
  • 14
  • 27