I tried to convert an iterator that should return a single item to an equivalent option.
The best I could do was this. Should I use something from standard API?
def toUniqueOption[T](a: Iterator[T]): Option[T] =
if (a.size > 1)
throw new RuntimeException("The iterator should be emtpy or contain a single item but contained ${a.size} items.")
else if (a.size > 0)
Option(a.toList(0))
else
Option.empty
Updated with try
def toUnique[T](a: Iterator[T]): Try[Option[T]] =
if (a.size > 1)
Failure(new RuntimeException("The iterator should be emtpy or contain a single item but contained ${a.size} items."))
else if (a.size > 0)
Success(Option(a.toList(0)))
else
Success(Option.empty)
Calling size
is risky because it isn't guaranteed to be efficient or even halt.
How about:
def toUniqueOption[T](a: Iterator[T]): Option[T] =
a.take(2).toList match {
case Nil => None
case x :: Nil => Some(x)
case _ => throw new RuntimeException("Iterator size > 1")
}
You could actually use standard API:
a.toStream.headOption
where a: Iterator[T]
Edit: with scala 2.13+ just use a.nextOption()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With