Skip to content

Instantly share code, notes, and snippets.

@dportabella
Last active December 18, 2015 10:09
Show Gist options
  • Save dportabella/5766099 to your computer and use it in GitHub Desktop.
Save dportabella/5766099 to your computer and use it in GitHub Desktop.
Transform a callback function to an iterator/list (in Scala or Java). See an example use case: http://scalaenthusiast.wordpress.com/2013/06/12/transform-a-callback-function-to-an-iteratorlist-in-scala/
import java.util.concurrent.ArrayBlockingQueue
trait OptionNextToIterator[T] extends Iterator[T] {
def getOptionNext: Option[T];
var answerReady: Boolean = false
var eof: Boolean = false
var element: T = _
def hasNext = {
prepareNextAnswerIfNecessary
!eof
}
def next = {
prepareNextAnswerIfNecessary
if (eof) { throw new NoSuchElementException }
val retVal = element
answerReady = false
retVal
}
def prepareNextAnswerIfNecessary {
if (answerReady) {
return
}
synchronized {
getOptionNext match {
case None => eof = true
case Some(e) => element = e
}
answerReady = true
}
}
}
trait QueueToIterator[T] extends OptionNextToIterator[T] {
val queueCapacity: Int
val queue = new ArrayBlockingQueue[Option[T]](queueCapacity)
var queueClosed = false
def queuePut(entry: T) {
if (queueClosed) { throw new IllegalStateException("The queue has already been closed."); }
queue.put(Some(entry))
}
def queueClose() {
queueClosed = true
queue.put(None)
}
def getOptionNext = queue.take
}
@dportabella
Copy link
Author

Transform a callback function to an iterator/list (in Scala)
See an example use case:
http://scalaenthusiast.wordpress.com/2013/06/12/transform-a-callback-function-to-an-iteratorlist-in-scala/

@dportabella
Copy link
Author

if someone is interested, this can easily be transformed to Java.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment