Issue
I was having a look at the Iterable interface in Kotlin (kotlin.collections) and noticed that it has one function - the iterator function which returns an Iterator. However, I also noticed that it has the operator keyword. As far as I understand from the kotlin docs (correct me if I'm wrong) the operator keyword is used for syntactic sugar e.g. operator fun of a.plus(b) enables us to write a + b instead of writing a.plus(b). So, I was wondering, what is the 'syntactic shortcut' if it exists for the iterator() function? Or is there another purpose I'm unaware of? I couldn't find anything about this in the documents.
Solution
The documentation for for
-loops (not the docs for operator overloading you might have looked at) provides the answer:
As mentioned before, for iterates through anything that provides an iterator. This means that it:
- has a member or an extension function
iterator()
that returnsIterator<>
:- has a member or an extension function
next()
- has a member or an extension function
hasNext()
that returns Boolean.All of these three functions need to be marked as
operator
.
The for
-loop requires the iterator()
, next()
and hasNext()
methods to be marked with operator
. This is another use of the operator
keyword besides overloading operators.
For JVM interobility, Java classes implementing java.util.Iterable
don't need the operator
keyword on the iterator()
method because it doesn't exist in Java (and this makes it possible to iterate over Java Iterable
s from Kotlin code).
Answered By - dan1st
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.