% ./bin/scala -deprecation
Welcome to Scala 3.1.3 (18.0.1, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala> Int.MaxValue+1
val res0: Int = -2147483648
I’m a newcomer to scala. Is there a solution to prompt me the integer overflow situation in scala 3 REPL, instead of getting the wrong calculation result.
1 Like
You can use the BigInt
type to avoid overflows entirely. BigInt
does not have a max or min value.
Otherwise, what you want can be accomplished by writing some code to detect the overflow. The book “Programming in Scala 5th Ed.” discusses this a bit:
You usually don’t want to trigger an actual exception in functional programming. Instead you can use an Option
type. This is just one example, for absolute value function:
If you are new to Scala, I strongly recommend picking up this book! You can find answers to pretty much all your questions there.
3 Likes
Many thanks to your detailed, helpful explanations and recomendation. It seems that I get your points. BTW, I’m reading the the first half part of book “Programming in Scala 5th Ed.”.
2 Likes
You may find the methods that ends with Exact
in the math package useful. They throw exceptions when calculations go bad due to overflow etc:
scala> math.addExact(Int.MaxValue, 1)
java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.addExact(Math.java:883)
at scala.math.package$.addExact(package.scala:400)
... 34 elided
scala> math. //press TAB
!= addExact getClass rint
## asInstanceOf getExponent round
-> asin hashCode scalb
== atan hypot signum
BigDecimal atan2 incrementExact sin
BigInt cbrt isInstanceOf sinh
E ceil log sqrt
Equiv copySign log10 subtractExact
Fractional cos log1p tan
IEEEremainder cosh max tanh
Integral decrementExact min toDegrees
Numeric ensuring multiplyExact toIntExact
Ordered equals negateExact toRadians
Ordering exp nextAfter toString
PartialOrdering expm1 nextDown ulp
Pi floor nextUp →
ScalaNumber floorDiv nn
abs floorMod pow
acos formatted random
5 Likes