Open Stephan202 opened 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.
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)
Oh, looks like you already have a CL out to do so!
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.
As of Java 8 there is
Math.toIntExact
. This method forms an alternative to Guava'sInts.checkedCast
, except that the former throws anArithmeticException
while the latter throws anIllegalArgumentException
.Suggestion: update the documentation of
Ints.checkedCast
to suggestMath.toIntExact
as an alternative for Java 8 users, pointing out the caveat that this would change the exception behavior.