/
RedundantElseInWhen.kt
81 lines (76 loc) · 2.37 KB
/
RedundantElseInWhen.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtWhenExpression
/**
* Turn on this rule to flag `when` expressions that contain a redundant `else` case. This occurs when it can be
* verified that all cases are already covered when checking cases on an enum or sealed class.
*
* <noncompliant>
* enum class Color {
* RED,
* GREEN,
* BLUE
* }
*
* fun whenOnEnumFail(c: Color) {
* when(c) {
* Color.BLUE -> {}
* Color.GREEN -> {}
* Color.RED -> {}
* else -> {}
* }
* }
* </noncompliant>
*
* <compliant>
* enum class Color {
* RED,
* GREEN,
* BLUE
* }
*
* fun whenOnEnumCompliant(c: Color) {
* when(c) {
* Color.BLUE -> {}
* Color.GREEN -> {}
* else -> {}
* }
* }
*
* fun whenOnEnumCompliant2(c: Color) {
* when(c) {
* Color.BLUE -> {}
* Color.GREEN -> {}
* Color.RED -> {}
* }
* }
* </compliant>
*/
@RequiresTypeResolution
@ActiveByDefault(since = "1.2.0")
@Deprecated("Rule deprecated as compiler performs this check by default")
class RedundantElseInWhen(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue(
"RedundantElseInWhen",
Severity.Warning,
"Check for redundant `else` case in `when` expression when used as statement.",
Debt.FIVE_MINS
)
override fun visitWhenExpression(whenExpression: KtWhenExpression) {
super.visitWhenExpression(whenExpression)
val elseEntry = whenExpression.entries.lastOrNull { it.isElse } ?: return
val compilerReports = bindingContext.diagnostics.forElement(elseEntry)
if (compilerReports.any { it.factory == Errors.REDUNDANT_ELSE_IN_WHEN }) {
report(CodeSmell(issue, Entity.from(whenExpression), "When expression contains redundant `else` case."))
}
}
}