Martin Stone Martin Stone -4 years ago 249
Android Question

Kotlin on Android: map a cursor to a list

In Kotlin, What's the best way to iterate through an Android Cursor object and put the results into a list?

My auto-converted Java:

val list = ArrayList<String>()
while (c.moveToNext()) {

Is there a more idiomatic way? In particular, can it be done in a single assignment of a read-only list? E.g....

val list = /*mystery*/.map(getStringFromCursor)

... or some other arrangement, where the list is assigned fully-formed.

Answer Source

This is what I went with in the end, using kotlin.sequences.generateSequence...

val list = generateSequence { if (c.moveToNext()) c else null }
        .map { getStringFromCursor(it) }

My first attempt was a little shorter:

val list = (1 .. c.count).map {

Both versions rely on the cursor initially being positioned before the first record. The second would throw if that wasn't the case, while the first would return a shorter list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download