KT.ITERATOR_NOT_THROWING_NO_SUCH_ELEMENT_EXCEPTION

Implementation of the Iterator interface does not throw a NoSuchElementException

Reports implementations of the Iterator interface which do not throw a NoSuchElementException in the implementation of the next() method. When there are no more elements to return an Iterator should throw a NoSuchElementException. See: https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#next()

Noncompliant Code

Copy
class MyIterator : Iterator<String> {

    override fun next(): String {
        return ""
    }
}

Compliant Code

Copy
class MyIterator : Iterator<String> {

    override fun next(): String {
        if (!this.hasNext()) {
            throw NoSuchElementException()
        }
        // ...
    }
}

The content on this page is adapted from the Detekt Docs. Copyright ©2022 The Detekt Team. All rights reserved. https://detekt.dev/comments.html