【问题标题】:Why is the iterator evaluated when creating a new Iterable from it?为什么从迭代器创建新的 Iterable 时会评估迭代器?
【发布时间】:2013-06-19 11:42:16
【问题描述】:
> scala> val myI = new Iterable[Int]{def iterator = Iterator.continually(1)} 
> java.lang.OutOfMemoryError: Java heap space
>   at java.util.Arrays.copyOf(Arrays.java:2882)    at
> <snip>

现在,这是预期的行为吗?我觉得这有点奇怪,它妨碍了我。

【问题讨论】:

    标签: scala scala-collections


    【解决方案1】:

    这只是 REPL 过于努力地提供帮助——它试图打印出你的新 Iterable 作为它在返回值时所做的一部分。您可以将其粘贴在某些不打印其内容的容器中,也可以覆盖 toString

    scala> val myI = new Iterable[Int] { def iterator = Iterator.continually(1); 
         |   override def toString = "myI" }
    myI: Iterable[Int] = myI
    

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2014-10-28
      • 1970-01-01
      • 2010-10-09
      • 2016-07-24
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      相关资源
      最近更新 更多