Inspectopedia Help

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

By default bundled with:

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin:

Kotlin, 241.16690-IJ

Last modified: 29 April 2024