将Scala ArrayBuffer转换为Iterator

时间:2016-10-25 14:54:10

标签: scala collections

我有一个接受输入的Scala方法,根据这些输入创建ArrayBuffer[Widget],但必须将该数组缓冲区转换为Iterator[Widget]

def createWidgetIterator(isFizz : Boolean, buzz : String) : Iterator[Widget] = {
    val widgetBuffer = new ArrayBuffer[Widget]()

    // ...Use some logic to add Widget instances to widgetBuffer
    // widgetBuffer += new Widget(...)     etc.

    // At this point widgetBuffer is full of Widget instances

    // TODO: Convert widgetBuffer to Iterator[Widget]
    val widgetIterator : Iterator[Widget] = null // ???

    widgetIterator
}

有人知道我怎么做这种转换吗?

1 个答案:

答案 0 :(得分:2)

在数组缓冲区上使用toIterator来获取迭代器

Scala REPL

scala> val ab = ArrayBuffer(1, 2)
ab: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2)

scala> ab.toIterator
res1: Iterator[Int] = non-empty iterator

代码

def createWidgetIterator(isFizz : Boolean, buzz : String) : Iterator[Widget] = {
    val widgetBuffer = new ArrayBuffer[Widget]()
    widgetBuffer.toIterator
}