Kotlin on Android: hover over a list

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

My automatic java conversion:

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

Is there a more idiomatic way? In particular, can this be done in a single read-only list assignment? For instance....

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

... or another location where the list is assigned to be fully formed.

+6
source share
7 answers

This is what I ended up using kotlin.sequences.generateSequence...

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

My first attempt was a little shorter:

val list = (1 .. c.count).map {
    c.moveToNext()
    getStringFromCursor(c)
}

, ( ). , , .

+12

Cursor , map. Anko (ANdroid KOtlin JetBrains) , Cursor.

Cursor.parseList(parser). . . sqlite anko.

+4

:

fun <T> Cursor.toArrayList(block: (Cursor) -> T) : ArrayList<T> {
    return arrayListOf<T>().also { list ->
        if (moveToFirst()) {
            do {
                list.add(block.invoke(this))
            } while (moveToNext())
        }
    }
}

:

val list = cursor.toArrayList { getStringFromCursor(it) }
+2

map() isClosed() Cursor , isClosed() :

fun <T> Cursor.map(f: (Cursor) -> T): List<T> {
  val items = mutableListOf<T>()
  use {
    while (!it.isClosed && it.moveToNext()) {
      items += f(it)
    }
  }
  return items.toList()
}

:

val contacts = cursor.map { it.toContact() }
+1

. .

0

, , Anko. : , inline , parseRow .

private inline fun <T> getObjectListFromCursor(cursor: Cursor, parseRow: (Cursor) -> T): List<T> {
        return cursor.run {
            mutableListOf<T>().also { list ->
                if (moveToFirst()) {
                    do {
                        list.add(parseRow(this))
                    } while (moveToNext())
                }
                close()
            }
        }
    }

:

val list = getObjectListFromCursor(c, this::getStringFromCursor)
0

cursor.moveToFirst()
val list = generateSequence {
    cursor.moveToNext()
    getStringFromCursor(cursor)
}.take(cursor.count).toList()
0
source

Source: https://habr.com/ru/post/1651943/


All Articles