Kotlin java.lang.Math.incrementExact
Add one while checking whether an integer counter has reached its limit.
A simple example
java.lang.Math.incrementExact
- Start with 3
- Do this Add 1
- Result 4
fun main() {
println(java.lang.Math.incrementExact(3))
}
4
Syntax
java.lang.Math.incrementExact(ticket)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarIssue the next numbered ticket
A desk issues numbered places one at a time. Check the next or remaining count at the edge of its allowed range so a full counter cannot wrap into an apparently valid booking.
fun main() {
val ticket = 99
println(java.lang.Math.incrementExact(ticket))
}
100
After ticket 99 the next number is 100.
Issue a coat-check ticket
The last tag used at a school concert was 249. The next guest needs the following consecutive number.
Using 249 gives 250 for this measurement.
Number the next lab sample
A class has recorded sample 79. A student adds one to assign the next identifier.
Using 79 gives 80 for this measurement.
What to watch for
An out-of-range integer result raises ArithmeticException. Decide how the caller should handle that failure.