Skip to content

Commit

Permalink
Replace 'when' with 'if': do not suggest if 'when' is used as express…
Browse files Browse the repository at this point in the history
…ion and it has no 'else' branch

#KT-35329 Fixed
  • Loading branch information
t-kameyama authored and vladimirdolzhenko committed Apr 15, 2020
1 parent 893021f commit 77b6881
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 77b6881

Please sign in to comment.