加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何转换scala Iterator [T]到Option [T]

发布时间:2020-12-16 09:08:36 所属栏目:安全 来源:网络整理
导读:我试图将应该返回单个项目的迭代器转换为等效选项. 我能做的最好的就是这个.我应该使用标准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
我试图将应该返回单个项目的迭代器转换为等效选项.

我能做的最好的就是这个.我应该使用标准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)

解决方法

呼叫大小是有风险的,因为它不能保证有效甚至停止.

怎么样:

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")
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读