Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?

后端 未结 3 1301
渐次进展
渐次进展 2021-01-31 04:06

Is it possible to use yield as an iterator without evaluation of every value?

It is a common task when it is easy to implement complex list generation, and then you need

3条回答
  •  梦如初夏
    2021-01-31 04:38

    I have a List...

    scala>  List(1, 2, 3)
    res0: List[Int] = List(1, 2, 3)
    

    And a function...

    scala> def foo(i : Int) : String = { println("Eval: " + i); i.toString + "Foo" }
    foo: (i: Int)String
    

    And now I'll use a for-comprehension with an Iterator...

    scala> for { i <- res0.iterator } yield foo(i)
    res2: Iterator[java.lang.String] = non-empty iterator
    

    You can use a for comprehension on any type with flatMap, map and filter methods. You could also use the views:

    scala> for { i <- res0.view } yield foo(i)
    res3: scala.collection.SeqView[String,Seq[_]] = SeqViewM(...)
    

    Evaluation is non-strict in either case...

    scala> res3.head
    Eval: 1
    res4: String = 1Foo
    

提交回复
热议问题