2

I have a requirement to store only positive values. As I understand, signed can store both positive and negative values. Are there any unsigned integer, double data types in Scala?

Regards

Pratap D
  • 311
  • 3
  • 7
  • 14

3 Answers3

6

There was a proposal to include new data types for unsigned Int in scala, but it was going to have a performance impact. Hence the people who maintain scala decided not to go ahead with the proposal of an unsigned Int in scala.

Please refer the following https://docs.scala-lang.org/sips/unsigned-integers.html

You may also refer Unsigned variables in Scala.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Chaitanya
  • 3,590
  • 14
  • 33
  • The link above is broken. could you fix that? https://docs.scala-lang.org/sips/rejected/unsigned-integers.html – Yuchen Jan 14 '20 at 18:00
  • Now neither of the links work. The updated link is https://github.com/scala/improvement-proposals/pull/27 – lezsakdomi Mar 25 '23 at 00:17
1

Scala doesn't own unsigned int but you can use spire library, they have UByte, UShort, UInt, and ULong etc. Please have a look here https://github.com/non/spire/blob/master/GUIDE.md

Amit Prasad
  • 725
  • 4
  • 17
0

Scala doesn't support Unsigned integers, but you can have a workaround like this.

scala> val x = 2147483647
x: Int = 2147483647

scala> val y = x+4
y: Int = -2147483645

Here you want to have the value of y as 2147483651 instead of the negative value limited by the Integer type. To get the positive value, you can use the BigInt library. Get the byte sequence of the Integer Value and prefix it with another "zero", so that the entire value now becomes positive.

scala> import scala.math.BigInt
import scala.math.BigInt

scala> val prefix:Array[Byte]=Array(0)
prefix: Array[Byte] = Array(0)

scala> val y = BigInt(prefix ++ BigInt(x+4).toByteArray)
y: scala.math.BigInt = 2147483651

scala>

You can wrap it as a function like this

scala> def unsignedInt(a:Integer):scala.math.BigInt=
     | {
     |  val prefix:Array[Byte]=Array(0)
     |  BigInt(prefix ++ BigInt(a).toByteArray)
     | }
unsignedInt: (a: Integer)scala.math.BigInt

scala> unsignedInt(x)+unsignedInt(4)
res31: scala.math.BigInt = 2147483651

scala>
stack0114106
  • 8,534
  • 3
  • 13
  • 38