Looking for headOption for Iterator

Is there an analogous method to headOption for Iterator?
I have an Iterator and I’m not sure whether it is empty, so I want an Option of its first element.
I can do the following, because I don’t see a better way.

if (it.isEmpty)
  None
else
  Some(it.next())

BTW is that the same as:

if (it.hasNext)
  None
else
  Some(it.next())

There is nextOption which is basically what you implemented yourself.

And BufferedIterator allows peeking at the first element with head or headOption, but as the name says it will buffer the head instead of consuming it like a regular Iterator.

You can convert any Iterator to a BufferedIterator with it.buffered. Beware that—like most methods on Iterator—you should discard the original Iterator after calling buffered.

1 Like

When was nextOption added? I don’t seem to have such a method.

Looks like it was added in 2.13.

1 Like

Kudos to the 2.13 maintainers!

Between you and me, I suspect you can use it.buffered.headOption as a drop-in replacement for it.nextOption. But it’s not guaranteed to never blow up in your face, as the official rule is still "discard the original Iterator after calling buffered".

But perhaps you actually do want to peek instead of consume the first element. In that case you can just use buffered as intended.