diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryVariableInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryVariableInspection.kt index 48711a6318a..85498ac3bfe 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryVariableInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryVariableInspection.kt @@ -67,30 +67,29 @@ class UnnecessaryVariableInspection : AbstractKotlinInspection() { val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(property) ?: return null val initializer = property.initializer ?: return null - if (!property.isVar && initializer is KtNameReferenceExpression && property.typeReference == null) { - val context = property.analyze() - val initializerDescriptor = context[REFERENCE_TARGET, initializer] - if (initializerDescriptor is VariableDescriptor) { - if (!initializerDescriptor.isVar && initializerDescriptor.containingDeclaration is FunctionDescriptor) { - if (ReferencesSearch.search(property, LocalSearchScope(enclosingElement)).findFirst() != null) { - return Status.EXACT_COPY - } - } + fun isExactCopy(): Boolean { + if (!property.isVar && initializer is KtNameReferenceExpression && property.typeReference == null) { + val context = property.analyze() + val initializerDescriptor = context[REFERENCE_TARGET, initializer] as? VariableDescriptor ?: return false + if (initializerDescriptor.isVar) return false + if (initializerDescriptor.containingDeclaration !is FunctionDescriptor) return false + return ReferencesSearch.search(property, LocalSearchScope(enclosingElement)).findFirst() != null } + return false } - val nextStatement = property.getNextSiblingIgnoringWhitespaceAndComments() - if (nextStatement is KtReturnExpression) { - val returned = nextStatement.returnedExpression - if (returned is KtNameReferenceExpression) { - val context = nextStatement.analyze() - if (context[REFERENCE_TARGET, returned] == context[DECLARATION_TO_DESCRIPTOR, property]) { - return Status.RETURN_ONLY - } - } + fun isReturnOnly(): Boolean { + val nextStatement = property.getNextSiblingIgnoringWhitespaceAndComments() as? KtReturnExpression ?: return false + val returned = nextStatement.returnedExpression as? KtNameReferenceExpression ?: return false + val context = nextStatement.analyze() + return context[REFERENCE_TARGET, returned] == context[DECLARATION_TO_DESCRIPTOR, property] } - return null + return when { + isExactCopy() -> Status.EXACT_COPY + isReturnOnly() -> Status.RETURN_ONLY + else -> null + } } fun isActiveFor(property: KtProperty) = statusFor(property) != null