我试图将应该返回单个项目的迭代器转换为等效选项。
我能做的最好的事情就是这个。我应该使用标准 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
使用尝试更新
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)
调用size
是有风险的,因为它不能保证有效甚至停止。
怎么样:
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")
}
你实际上可以使用标准API:
a.toStream.headOption
其中 a:迭代器[T]
编辑:使用 scala 2.13+ 只需使用 a.nextOption()
您可以避免使用 hasNext
和 next
迭代整个序列:
def toUniqueOption[T](a: Iterator[T]): Option[T] = {
if(a.hasNext) {
val f = a.next()
if(a.hasNext) throw new RuntimeException("Iterator should contain at most one element")
Some(f)
}
else None
}
不完全是你要求的,但为什么不使用这样的东西:
def nextAsOption[T](i: Iterator[T]) : Option[T] = {
i.hasNext match {
case true => Some(i.next)
case false => None
}
}
这只为您提供了一个迭代器"下一个"操作,该操作返回一个选项而不是布尔值。当你需要传递选项时非常方便。