diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt index b0bdbe3a36d..2c81189f853 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt @@ -82,8 +82,12 @@ fun match(loop: KtForExpression): ResultTransformationMatch? { for (matcher in MatcherRegistrar.sequenceMatchers) { val match = matcher.match(state) if (match != null) { + val newState = match.newState + // check that old working variable is not needed anymore + if (state.workingVariable != newState.workingVariable && state.workingVariable.hasUsages(newState.statements)) return null + sequenceTransformations.addAll(match.transformations) - state = match.newState + state = newState continue@MatchLoop } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt index f93b41edf3c..76439b83009 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt @@ -61,7 +61,6 @@ class FlatMapTransformation( if (iterableType.checkIsSuperTypeOf(nestedSequenceType) == null) return null val nestedLoopBody = nestedLoop.body ?: return null - if (state.workingVariable.hasUsages(nestedLoopBody)) return null // workingVariable is still needed - cannot transform val newWorkingVariable = nestedLoop.loopParameter ?: return null val transformation = FlatMapTransformation(state.workingVariable, transform) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt index 1d1142852e8..601c4335eae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt @@ -49,7 +49,6 @@ class MapTransformation( val initializer = declaration.initializer ?: return null if (declaration.hasWriteUsages()) return null val restStatements = state.statements.drop(1) - if (state.workingVariable.hasUsages(restStatements)) return null // workingVariable is still needed - cannot transform to map() val transformation = MapTransformation(state.workingVariable, initializer) val newState = state.copy(statements = restStatements, workingVariable = declaration)