How to annotate Collection.toArray(T[])
#481
Labels
library-use-case
Question of how a particular library should be annotated; could potentially affect design or docs
nullness
For issues specific to nullness analysis.
Milestone
Currently using the signature:
Originally posted by @cpovirk in #65 (comment)
Concretely, it seems like the alternatives would be:
1:
I'd already said a little about that alternative above, but: The theory would be that, because the collection might contain nulls or your array might be too large, we might end up inserting a null into the array no matter what. So we at least give it back to you as an array of nullables. But of course you might pass an input array of non-nullables and then choose to use it afterward. That would be unsound but nothing that you couldn't have done to yourself already through array covariance if you had wanted to.
The downside is the inconvenience of the array-of-nullables return type when you know it's not necessary.
2:
With this signature, we'd be allowing you to pass any array type but then give it back to you as an array of non-nullables, thereby giving you the option to either use that type (if you know it's safe) or re-widen it (if not).
The downside is that you might go to the trouble of passing an array of nullables to be safe but then not realize that the nullability is lost along the way.
3:
This is dangerous is ways similar to (2) but even more inconvenient for someone who is trying to do the right thing and pass a nullable array. I guess the case for it would rest on the idea that most collections don't contain nulls and most inputs are only type tokens, so why complicate the picture with nullness, especially when covariant arrays throw it all out the window?
(I think I see even less case for a potential (4)
<T> @Nullable T[] toArray(T[])
? Like, if you're arguing that the return type needs to reflect that the array might have nulls in it, then why not even optionally allow the input type to reflect that, too?)(Maybe I'm overlooking other signatures in which
<T extends @Nullable Object>
could be useful?)Does any of that strike your fancy? I think I'm still happy with the current signature, but I'm not dead certain.
The text was updated successfully, but these errors were encountered: