Last active
December 18, 2015 10:09
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
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/