Search code examples
kotliniteratoroperator-overloadingoperator-keyworditerable

Why is the 'operator' keyword optional on hasNext(), next() and iterator() in Kotlin?


I was building my own collection and when I was implementing Iterable, I realized that I forgot to put the operator keyword onto the iterator() method in my collection and also the two methods hasNext() and next() in my Iterator. The code still worked just fine, with or without the operator keyword. Now, I do understand why these methods are operator methods. I just want to know why they chose to make it an operator method and then not force the user to use the operator keyword next to it.


Solution

  • Based on Tenfour04's answer and my own findings, I realized that the reason why I'm not forced to use the operator keyword is because I'm inheriting from Kotlin's Iterable and Iterator. And these interfaces already contain the methods iterator(), hasNext() and next() with the keyword operator next to them. As the Kotlin Docs state:

    When overriding your operator overloads, you can omit operator.

    And, the reason why these methods require you to use the operator keyword is because you are not forced to inherit from Iterable and Iterator. In Kotlin, you are welcome to create your own custom CustomIterable and CustomIterator, in which you will be forced to use the operator keyword next to the methods if you want to use the foreach loop. However, not inheriting from Iterable means you won't have available any of the Kotlin's useful methods for collection operations like .forEach { … }, .map { … }, .filter { … } etc.