Back to Intellij Community

UseWithIndex

plugins/kotlin/code-insight/descriptions/resources-en/inspectionDescriptions/UseWithIndex.html

2025.3-rc-2735 B
Original Source

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
  }