getActivity().finish();
Now editor shows warning where the method is annotated with @Nullable
. Then it shows suggestion to use requireNonNull
. When I accept its changes then it converts code to this, and warning is gone.
Objects.requireNonNull(getActivity()).finish();
Does it make sense to use requireNonNull
?
Implementation of requireNonNull
is
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
So my code will still crash if getActivity()
is null.
We should null check for this.
if (getActivity() != null)
getActivity().finish();
I think null check
is better than requireNonNull
, what you say? If yes, then editor should not suggest to use requireNonNull
there.
Because it is not safe to use requireNonNull in fields having state like Activity
. Am I missing some benefit of requireNonNull
?