Is there a neat way to create an unsigned variable using scala value classes?
case class Size(val size: Int) extends AnyVal {
....
}
Is there a neat way to create an unsigned variable using scala value classes?
case class Size(val size: Int) extends AnyVal {
....
}
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])
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
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
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.
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) ...
}