KT.REDUNDANT_ELSE_IN_WHEN

Redundant 'else' case in 'when' expression

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 Code

Copy
enum class Color {
    RED,
    GREEN,
    BLUE
}

fun whenOnEnumFail(c: Color) {
    when(c) {
        Color.BLUE -> {}
        Color.GREEN -> {}
        Color.RED -> {}
        else -> {}
    }
}

Compliant Code

Copy
<cde>
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 -> {}
    }
}

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html