Skip to content

Contract checking does not work for @Contract("null -> null") #1121

@agrieve

Description

@agrieve

I'd like to say that if the given method returns non-null, then the passed in value is non-null.

    @Contract("null -> null")
    public static @Nullable Activity activityFromContext(@Nullable Context context) {
        // Only retrieves the base context if the supplied context is a ContextWrapper but not an
        // Activity, because Activity is a subclass of ContextWrapper.
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) return (Activity) context;

            context = ((ContextWrapper) context).getBaseContext();
        }

        return null;
    }

But this still gives a warning:

        if (ContextUtils.activityFromContext(context) != null) {
            mDialogCore = new DialogOverlayCore();
            // Complains that context is nullable:
            mDialogCore.initialize(context, mConfig, DialogOverlayImpl.this, mAsPanel);
            mDialogCore.onWindowToken(window.getWindowToken());
        }

I suspect this might fall under:

Not all possible clauses of @Contract annotations are fully parsed or supported by NullAway

If so, it'd be great to update the docs to say that contract support cannot infer parameters based on nullness of return types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions