Library contents

Scala java.lang.Math.toIntExact

Convert a long count to int only when its value is representable.

A simple example

java.lang.Math.toIntExact

  1. Start with 7 as a long integer
  2. Do this Convert to a narrower integer
  3. Result 7
Seven is in range, so conversion preserves its value.
Lesson.scala
object Lesson extends App {
    println(java.lang.Math.toIntExact(7L))
}
Output
7

Syntax

Scala 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 Lesson

Fit 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.

From the programval tickets = 42000L
Result42000
Lesson.scala

object Lesson {
    def main(args: Array[String]): Unit = {
        val tickets = 42000L
        println(java.lang.Math.toIntExact(tickets))
    }
}
Output
42000

A batch of 42000 tickets fits in an int.

Advertisements

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.

Given650
Worked result650

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.

Given128
Worked result128

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.

Documentation for java.lang.Math.toIntExact