introduce functional variable: warn about non-finals (IDEA-174449)

non-final variables won't be accessible inside lambda/anonymous class, thus must be passed as parameters to SAM
This commit is contained in:
Anna Kozlova
2017-06-15 13:52:54 +03:00
parent d8595269f4
commit 46e403bfa1
2 changed files with 15 additions and 7 deletions
@@ -162,7 +162,7 @@ public class ExtractMethodDialog extends DialogWrapper implements AbstractExtrac
@Override
public String getChosenMethodName() {
return myNameField.getEnteredName();
return myNameField.getEnteredName().trim();
}
@Override
@@ -613,9 +613,8 @@ public class ExtractMethodDialog extends DialogWrapper implements AbstractExtrac
PsiMethod prototype;
try {
PsiElementFactory factory = JavaPsiFacade.getInstance(myProject).getElementFactory();
prototype = factory.createMethod(myNameField.getEnteredName().trim(), myReturnType);
prototype = factory.createMethod(getChosenMethodName(), myReturnType);
if (myTypeParameterList != null) prototype.getTypeParameterList().replace(myTypeParameterList);
Set<String> usedNames = new HashSet<>();
for (VariableData data : myInputVariables) {
if (data.passAsParameter) {
prototype.getParameterList().add(factory.createParameter(data.name, data.type));
@@ -633,10 +632,8 @@ public class ExtractMethodDialog extends DialogWrapper implements AbstractExtrac
protected void checkParametersConflicts(MultiMap<PsiElement, String> conflicts) {
Set<String> usedNames = new HashSet<>();
for (VariableData data : myInputVariables) {
if (data.passAsParameter) {
if (!usedNames.add(data.name)) {
conflicts.putValue(null, "Conflicting parameter name: " + data.name);
}
if (data.passAsParameter && !usedNames.add(data.name)) {
conflicts.putValue(null, "Conflicting parameter name: " + data.name);
}
}
}
@@ -17,6 +17,7 @@ package com.intellij.refactoring.introduceVariable;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.FunctionalInterfaceSuggester;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.codeInspection.AnonymousCanBeLambdaInspection;
import com.intellij.ide.util.PsiClassListCellRenderer;
@@ -278,6 +279,16 @@ public class IntroduceFunctionalVariableHandler extends IntroduceVariableHandler
@Override
protected void checkMethodConflicts(MultiMap<PsiElement, String> conflicts) {
checkParametersConflicts(conflicts);
for (VariableData data : getChosenParameters()) {
if (!data.passAsParameter) {
PsiElement scope = PsiUtil.getVariableCodeBlock(data.variable, null);
if (PsiUtil.isLanguageLevel8OrHigher(data.variable)
? scope != null && !HighlightControlFlowUtil.isEffectivelyFinal(data.variable, scope, null)
: data.variable.hasModifierProperty(PsiModifier.FINAL)) {
conflicts.putValue(null, "Variable " + data.name + " is not effectively final and won't be accessible inside functional expression");
}
}
}
}
@NotNull