Repository navigation
Description
Currently using the signature:
<T extends @Nullable Object> T[] toArray(T[])Originally posted by @cpovirk in #65 (comment)
Concretely, it seems like the alternatives would be:
1:
<T> @Nullable T[] toArray(@Nullable T[])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:
<T> T[] toArray(@Nullable T[])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:
<T> T[] toArray(T[])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.
Activity
kevinb9n commentedon Feb 12, 2024
(So far I've been treating issues like this (how to annotate certain libraries) as though they are proper JSpecify design questions. The idea being that how we resolve this could have an effect on how we specify or even just document things.)
Mooninaut commentedon Apr 16, 2024
I don't see any option but 1. as being viable without a way to statically distinguish between a null-safe zero-length array argument and a null-unsafe positive-length array. If you want a
T![]!from aCollection<T!>you can and should use thetoArray(IntFunction<T[]> generator)overload.cpovirk commentedon Nov 23, 2026
(more on the
IntFunctionoverload)