If canChurn works as it should:
def func(churner: ItemChurner) = {
val iterator = new Iterator {
def hasNext = churner.canChurn
def next = churner.churn()
}
iterator.toList
}
About version (of the question) that contained catched exception check for churn():
If really expect some exceptions, what's the point of canChurn then?
Anyway, if you care about exceptions:
Iterator.continually(Try(churner.churn)).takeWhile(_.isSuccess).map(_.get).toList
This actually is not much precise, as churn might throw some other exception that has to be propagated, so here the scala's Exception helpers) come in hand:
def step = catching(classOf[NoMoreElementsException]) opt churner.churn()
Iterator.continually(step).takeWhile(_.nonEmpty).map(_.get).toList
Iteratorinterface likeval iterator = new Iterator {def hasNext = ItemChurner.canChurn; def next = ItemChurner.churn(), and theniterator.toListwhileloop with a try-catch? Shouldn'tItemChurnerreturnfalseif there aren't anymore elements?