Why is this an issue?
The Kotlin when
statement can not only be used to compare a selector against a list of values, but also to select from a list of
conditions.
This is a more readable and elegant alternative to a chain of if
statements and should be used instead.
What is the potential impact?
Readability and Understanding
This change makes it easier to understand a function because it will reduce its complexity. This is because a single when
statement
has less cognitive complexity than multiple if
statements, even if it has as many cases.
How to fix it
Refactor the chain of if
statements into a list of conditions for a when
statement. Note that the order of the conditions
must stay the same as in the if
chain.
Code examples
Noncompliant code example
fun dispatchFunction(instance: Any) {
if (instance is Foo) {
instance.fooFunction()
} else if (instance is Bar) {
instance.barFunction()
} else if (instance is Boo) {
instance.booFunction()
} else {
throw IllegalArgumentException()
}
}
Compliant solution
fun dispatchFunction(instance: Any) {
when (instance) {
is Foo -> instance.fooFunction()
is Bar -> instance.barFunction()
is Boo -> instance.booFunction()
else -> throw IllegalArgumentException()
}
}
Noncompliant code example
When threshold = 2
fun compare(a: Int, b: Int): Int {
// ...
return if (a > b) { // Noncompliant
1
} else if (a < b) {
-1
} else {
0
}
}
Compliant solution
fun compare(a: Int, b: Int): Int {
// ...
return when { // Compliant
a > b -> 1
a < b -> -1
else -> 0
}
}
Resources
Documentation
Articles & blog posts