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?
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With