google / guava

Google core libraries for Java
Apache License 2.0
50.07k stars 10.86k forks source link

`Ints.checkedCast` vs. `Math.toIntExact` #3105

Open Stephan202 opened 6 years ago

Stephan202 commented 6 years ago

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.

lowasser commented 6 years ago

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.

kluever commented 6 years ago

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 commented 6 years ago

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

cpovirk commented 1 month ago

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.