Search code examples
kotlinjdbcsequenceresultset

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?


Solution

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