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

scala – 为什么选项不直接扩展Iterable trait?

发布时间:2020-12-16 09:31:54 所属栏目:安全 来源:网络整理
导读:Option可以隐式地转换成一个Iterable,但是为什么它不只是直接实现Iterable呢? def iterator = new Iterator[A] { var end = !isDefined def next() = { val n = if (end) throw new NoSuchElementException() else get end = true n } def hasNext = !end}
Option可以隐式地转换成一个Iterable,但是为什么它不只是直接实现Iterable呢?

def iterator = new Iterator[A] {
  var end = !isDefined
  def next() = {
    val n = if (end) throw new NoSuchElementException() else get
    end = true
    n
  }

  def hasNext = !end
}

编辑:实际上它甚至比这更糟糕,因为在2.8选项确实声明一个迭代器方法:

def iterator: Iterator[A] = 
  if (isEmpty) Iterator.empty else Iterator.single(this.get)

解决方法

我在想,有太多不需要的无意义的方法。例如,您将期望返回值为:

Some(1) ++ Some(2)

目前,它通过2.8中的隐含方式编译并评估List(1,2),但似乎很奇怪。

也许这就是为什么文档在2.7中的评论说:

Only potentially unbounded collections should directly sub-class Iterable

编辑:如下面的@ MattR的评论所示,我将文档评论推荐留给子类型Collection可能会导致误导。而且考虑到这个问题变成“为什么选项不能扩展收藏特征?”

(编辑:李大同)

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

    推荐文章
      热点阅读