smeeb smeeb - 1 month ago 15
Scala Question

Convert Scala ArrayBuffer to Iterator

I have a Scala method that accepts inputs, creates an

ArrayBuffer[Widget]
based on those inputs, but then must convert that array buffer into an
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
}


Anybody know how I can do this type of conversion?

Answer

Use toIterator on array buffer to get an iterator

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

For your code

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