Producing a List from a ResultSet

Viewed 5133

I'm not entirely sure this is possible, and I definitely don't know what to search or how to concisely explain it, but this seems like quite a kotlin-y thing which I wouldn't be surprised if it was possible.

I want to instantiate a list with listOf() but instead of providing the elements for the list, providing some code which produces the elements for the list.

For example, using a ResultSet: (This isn't valid code)

val list: List<Int> = listOf(
    while(resultSet.next()){
        return resultSet.getInt(1)
    }
)

Is something like this possible?

4 Answers

Since kotlin 1.3

sequence {
    while (rs.next()) {
        yield(rs.getString(1))
    }
}.toList(

The sequence approach can be made a bit more general by factoring out the value "extraction":

fun <T> ResultSet.asSequence( extract: () -> T ) : Sequence<T> = generateSequence {
        if (this.next()) extract() else null
    }

and then use it like so:

resultSet.asSequence { resultSet.getString(1) }
Related