i am looking at the code in scala/src/library/scala/collection/Iterator.scala, and when reading methods that create new iterators or do transformations on iterators, i noticed that they always call hasNext in the next method. for example:
def tabulate[A](end: Int)(f: Int => A): Iterator[A] = new AbstractIterator[A] {
private var i = 0
def hasNext: Boolean = i < end
def next(): A =
if (hasNext) { val result = f(i); i += 1; result }
else empty.next()
}
i always assumed usage of iterators involves calling hasNext before calling next. since next also always/often calls hasNext, this basically means hasNext gets called twice for every next invocation. is this really necessary?
is the jvm smart enough to optimize these redundant calls to hasNext?
could the iterator contract be such that hasNext should always be called before next, making the call to hasNext inside next unnecessary?
or maybe should i not even worry about this at all?
best, koert