Iterator.continually: unable to evaluate expression in Scala REPL

Does anyone have any ideas / explanations why the REPL gets stuck while evaluating the last expression? The strange thing is that he does not throw anything or nothing, just nothing happens.

Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40).

scala> val empty = Seq.empty[Int].iterator
empty: Iterator[Int] = empty iterator

scala> val emptyInfiniteIterator = Iterator.continually(empty).flatten

Thanks in advance for any explanation.

+4
source share
1 answer

This is what happens. When you define an iterator in a Scala REPL, some information about this iterator is printed, whether empty or not in particular:

scala> Iterator.continually(List(1)).flatten
res1: Iterator[Int] = non-empty iterator

This information is returned by a method toString Iteratorthat is defined as follows:

override def toString = (if (hasNext) "non-empty" else "empty")+" iterator"

Basically, hasNextcalled for a newly created iterator. Now let's see what hasNext( scala.collection.TraversableOnce.FlattenOps#flatten) does in your case :

  class FlattenOps[A](travs: TraversableOnce[TraversableOnce[A]]) {
    def flatten: Iterator[A] = new AbstractIterator[A] {
      val its = travs.toIterator
      private var it: Iterator[A] = Iterator.empty
      def hasNext: Boolean = it.hasNext || its.hasNext && { it = its.next().toIterator; hasNext }
      def next(): A = if (hasNext) it.next() else Iterator.empty.next()
    }
  }

! hasNext , , . , . , , REPL. StackOverflow, , Scala while.

+5

All Articles