Creating a list from a ResultSet

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

I want to instantiate a list using listOf()

, but instead of providing the items for the list, providing some code that creates the items for the list.

For example using ResultSet: (this is invalid code)

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

      

Is this possible?

+3


source to share


2 answers


ResultSet

has no better interface for this conversion. But it would look like this:

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 List

so that you can handle it lazily, you cannot use the .use()

autoclose 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 the experimental Kotlin 1.1 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()

+7


source


I just thought you could use it generateSequence

too. Support for Jason to get to him faster ^^

Here's what I came up with (not tested, but rather short):



val list = generateSequence {
    if(!resultSet.next()) null
    else resultSet.getInt(1)
}.toList()

      

+1


source







All Articles