Replace 'when' with 'if': do not suggest if 'when' is used as expression and it has no 'else' branch

#KT-35329 Fixed
This commit is contained in:
Toshiaki Kameyama
2019-12-06 23:17:54 +09:00
committed by Vladimir Dolzhenko
parent 893021f22b
commit 77b6881032
3 changed files with 19 additions and 0 deletions
@@ -9,10 +9,13 @@ import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.combineWhenConditions
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>(
KtWhenExpression::class.java,
@@ -25,6 +28,7 @@ class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>(
if (entries.any { it != lastEntry && it.isElse }) return null
if (entries.all { it.isElse }) return null // 'when' with only 'else' branch is not supported
if (element.subjectExpression is KtProperty) return null
if (!lastEntry.isElse && element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) return null
return element.whenKeyword.textRange
}
@@ -0,0 +1,10 @@
//IS_APPLICABLE: false
enum class E { X, Y, Z}
fun test(e: E) {
val i = <caret>when (e) {
E.X -> 1
E.Y -> 2
E.Z -> 3
}
}
@@ -2653,6 +2653,11 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
runTest("idea/testData/intentions/branched/ifWhen/whenToIf/whenWithoutElse.kt");
}
@TestMetadata("whenWithoutElseUsedAsExpression.kt")
public void testWhenWithoutElseUsedAsExpression() throws Exception {
runTest("idea/testData/intentions/branched/ifWhen/whenToIf/whenWithoutElseUsedAsExpression.kt");
}
@TestMetadata("whenWithoutSubject.kt")
public void testWhenWithoutSubject() throws Exception {
runTest("idea/testData/intentions/branched/ifWhen/whenToIf/whenWithoutSubject.kt");