Manually incremented index variable can be replaced with use of 'withIndex()'
Reports for
loops with a manually incremented index variable.
for
loops with a manually incremented index variable can be simplified with the withIndex()
function.
Use withIndex() instead of manual index increment quick-fix can be used to amend the code automatically.
Example:
fun foo(list: List<String>): Int? {
var index = 0
for (s in list) { <== can be simplified
val x = s.length * index
index++
if (x > 0) return x
}
return null
}
After the quick-fix is applied:
fun foo(list: List<String>): Int? {
for ((index, s) in list.withIndex()) {
val x = s.length * index
if (x > 0) return x
}
return null
}
Inspection Details | |
---|---|
Available in: | IntelliJ IDEA 2023.3, Qodana for JVM 2023.3 |
Plugin: | Kotlin, @snapshot@ |
Last modified: 13 July 2023