In the code below, IDEA displays a possible NPE warning for "((PsiVariable)element.getParent())". The "assert" QuickFix however doesn't work because element.getParent() could return a different value (null) for the second invocation. That's why the QuickFix doesn't fix anything
public class Test {
public void test(@NotNull PsiElement element) {
if (checkSomething(element)) {
// This doesn't remove the NPE warning:
// assert ((PsiVariable)element.getParent()) != null;
if (((PsiVariable)element.getParent()).getNameIdentifier() != null) {
// ...
}
}
}
private boolean checkSomething(@NotNull PsiElement element) {
return element.getParent() instanceof PsiVariable;
}
}
#1 Offering the QuickFix here seems to be a bug because IDEA doesn't realize that the expression is potentially non-constant. (It does realize this for similar expressions without the type cast).
#2 The QuickFix should actually be offered for any possible NPE-warning and automatically introduce a local variable for potentially non-constant expressions:
PsiVariable psiVariable = ((PsiVariable)element.getParent());
assert psiVariable != null;
if (psiVariable.getNameIdentifier() != null) {
// ...
}