Producing a List from a ResultSet
ResultSet
does not have the best interface for doing this type of transformation. But it would look something like:
val list = resultSet.use {
generateSequence {
if (resultSet.next()) resultSet.getInt(1) else null
}.toList() // must be inside the use() block
}
// resultSet is already closed automatically at this point
See also: generateSequence()
If you want to leave it as a Sequence
instead of a List
to process it lazily, you cannot use the .use()
auto-closing helper.
val seq = generateSequence {
if (resultSet.next()) resultSet.getInt(1) else null
}
// later remember to call resultSet.close(), since the resultSet is still open
With Kotlin 1.1 experimental coroutines you can:
val seq = buildSequence {
while (resultSet.next()) {
yield(resultSet.getInt(1))
}
// resultSet.close() might work ok here
}
// if not, later remember to resultSet.close()
See also: buildSequence()