Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing a List from a ResultSet

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?

like image 971
Steven Waterman Avatar asked Jun 01 '17 19:06

Steven Waterman


2 Answers

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()

like image 131
Jayson Minard Avatar answered Oct 17 '22 21:10

Jayson Minard


It just occured to me that you could use generateSequence too. Props to Jayson for getting to it quicker ^^

This is what I came up with (not tested, but fairly short):

val list = generateSequence {
    if(!resultSet.next()) null
    else resultSet.getInt(1)
}.toList()
like image 20
zsmb13 Avatar answered Oct 17 '22 21:10

zsmb13