I'm using Scala, and have a ResultSet with an unknown number of elements. I'd like to loop through the set, processing each row, and end up with an array of the processed elements. The function rs.next()
moves the pointer to the next element and returns true
if that element is a meaningful row and false
if that element is not (either after the last row, or the return was empty to begin with). So even though the following won't work, I'd like something structured like:
while (rs.next()) yield new foo(rs)
I tried the answer for this question, like so:
if (rs.next()) Iterator.continually(new foo(rs)).takeWhile(rs.next())
But this doesn't work because the element is created before the condition is checked, behaving as a do-while which has to process the first bad element. As written, it will create a foo
using the last element of the resultset but not return it and requires the initial rs.next()
to get started.
I have multiple other ways to approach this problem: another query to count the number of elements and then using take
, using a boolean var that's set equal to rs.next()
and then used to return a null element if false and also used for the takeWhile
, a mutable collection that is added to in a while loop, and so on.
But I feel like I must be missing something, because some part of each of those solutions feels inelegant. Is there a simple functional construction that will repeatedly check a condition, creating an element to add to an iterator so long as the condition is true?