Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Do we have a way to mark "result be null if a paramater be null otherwise notnull"?

11 views
Skip to first unread message

Xeno Amess

unread,
Feb 11, 2025, 8:50:06 AMFeb 11
to jspecify-discuss
because this is actually a very common situation.
but in jsr305 we can only have nullable, or nonnull, means a return value shall be either nullable or nonnull. but life always happened like this:(code from maven if you ask)
截图 2025-02-11 21-43-56.png

@Nullable
public static org.apache.maven.artifact.Artifact toArtifact(@Nullable Dependency dependency) {
if (dependency == null) {
return null;
}

org.apache.maven.artifact.Artifact result = toArtifact(dependency.getArtifact());
result.setScope(dependency.getScope());
result.setOptional(dependency.isOptional());

return result;
}

what we really want to mark is , [if the param dependency be null, then return value be null,otherwise if the param dependency be notnull, then the return value is nonnull].
but what we get is we can only mark it as [the param dependency can be null; and the return value can be null]
the coresponse meaning is lost...
so is there any ideas for this situations?
I know there be a way that to split another function named [toArtifactNonNull] or something, and mark it as nonnull in, nonnull out, yes it can work, though complex and somehow ugly.
we want to have something like @Nullable(expression="isNullable(dependency)") or something...

Chris Povirk

unread,
Feb 11, 2025, 9:00:04 AMFeb 11
to Xeno Amess, jspecify-discuss
We do not :(

Some tools/annotations do have support for this, such as @PolyNull in the Checker Framework and @Contract in the JetBrains annotations.

It is still something that we'd consider adding, but at this point, we're more focused on growing support and usage for the annotations that we already have. (Of course, having this feature would be another way to grow usage :))

(In general, I'd advise against defining APIs that pass null through. That is likely to work better with many existing tools and perhaps also with any future Java language feature for nullness. But there are times when it's appropriate. (By coincidence, I was editing one such API literally when your email arrived!) And of course we're stuck with APIs that already exist.)
Reply all
Reply to author
Forward
0 new messages