Scala java.lang.Math.toIntExact
Convert a long count to int only when its value is representable.
A simple example
java.lang.Math.toIntExact
- Start with 7 as a long integer
- Do this Convert to a narrower integer
- Result 7
object Lesson extends App {
println(java.lang.Math.toIntExact(7L))
}
7
Syntax
java.lang.Math.toIntExact(tickets)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonFit a batch count into an integer field
A system must store a batch or grid count in a fixed-width field. Check that the calculation and the final conversion fit before committing the value to the record.
object Lesson {
def main(args: Array[String]): Unit = {
val tickets = 42000L
println(java.lang.Math.toIntExact(tickets))
}
}
42000
A batch of 42000 tickets fits in an int.
Transfer a shelf count to a label printer
The warehouse stores inventory totals as 64-bit counts. The printer accepts a signed 32-bit count and this shelf contains 650 items.
Using 650 gives 650 for this measurement.
Export a class attendance count
An attendance database stores row counts as long integers. The reporting form expects a signed integer and today’s total is 128.
Using 128 gives 128 for this measurement.
What to watch for
Casting to int can discard high bits. This conversion reports out-of-range values.