guava icon indicating copy to clipboard operation
guava copied to clipboard

`Ints.checkedCast` vs. `Math.toIntExact`

Open Stephan202 opened this issue 7 years ago • 4 comments

As of Java 8 there is Math.toIntExact. This method forms an alternative to Guava's Ints.checkedCast, except that the former throws an ArithmeticException while the latter throws an IllegalArgumentException.

Suggestion: update the documentation of Ints.checkedCast to suggest Math.toIntExact as an alternative for Java 8 users, pointing out the caveat that this would change the exception behavior.

Stephan202 avatar Apr 07 '18 16:04 Stephan202

Hmmm. This feels a little weird, largely because most of our classes in primitives have a checkedCast method, and it's only Ints that has an equivalent in Java 8. Eh, I think it's still worth it.

lowasser avatar May 18 '18 21:05 lowasser

Should we consider adding this warning to the other (now obsolete) APIs in places like IntMath though? e.g., IntMath.checkedSubtract(a, b) -> Math.subtractExact(a, b)

kluever avatar May 20 '18 16:05 kluever

Oh, looks like you already have a CL out to do so!

kluever avatar May 20 '18 16:05 kluever

In an internal discussion, it came up that the exception type differs slightly (IllegalArgumentException vs. ArithmeticException), possibly complicating fully automated migrations. (This does actually matter in practice, as shown in https://github.com/google/guava/issues/1956.)

Another point raised was Android compatibility. But the method should be available even under old versions of Android without enabling library desugaring: It's always desugared.

cpovirk avatar Aug 12 '24 17:08 cpovirk