Kotlin

Kotlin

Made by DeepSource

Iterator implementation does not throw NoSuchElementException KT-W1033

Bug risk
Major
Autofix

NoSuchElementException is a runtime exception that should be thrown when the next() method is called on an iterator and there are no more elements to iterate over. This exception serves as a signal to the caller that there are no more elements in the collection.

If an iterator implementation does not throw this exception and the caller continues to call next(), it could result in unexpected behavior and can lead to bugs in the code. For example, the caller may assume that there are more elements to iterate over and try to perform operations on a null value or an invalid state.

To fix this issue, make sure that iterator implementations throw a NoSuchElementException when the next() method is called and there are no more elements to iterate over.

Bad Practice

class MyIterator : Iterator<String> {
  private var currentIndex = 0
  private val elements = listOf("a", "b", "c")

  override fun hasNext() = currentIndex < elements.size

  override fun next(): String {
    if (hasNext()) {
      val element = elements[currentIndex]
      currentIndex++
      return element
    }
    return "" // No NoSuchElementException thrown
  }
}

Recommended

class MyIterator : Iterator<String> {
  private var currentIndex = 0
  private val elements = listOf("a", "b", "c")

  override fun hasNext() = currentIndex < elements.size

  override fun next(): String {
    if (hasNext()) {
      val element = elements[currentIndex]
      currentIndex++
      return element
    }
    throw NoSuchElementException() // NoSuchElementException thrown
  }
}