https://kotlinlang.org logo
#random
Title
# random
p

Paul Woitaschek

08/28/2022, 3:13 PM
Kotlin is so beautiful K
❤️ 5
e

ephemient

08/28/2022, 7:44 PM
Copy code
private suspend fun SequenceScope<DocumentFile>.walk(root: DocumentFile) {
    yield(root)
    if (root.isDirectory) {
        for (child in root.listFiles()) {
            walk(child)
        }
    }
}
fun DocumentFile.walk() = sequence {
    walk(this@walk)
}
p

Paul Woitaschek

08/28/2022, 7:46 PM
Why are you writing this?
e

ephemient

08/28/2022, 7:47 PM
hit the wrong enter which posted early
but I'd rather use a single sequence scope than create many subsequences - still uses stack per recursive level, but less
p

Paul Woitaschek

08/28/2022, 7:58 PM
Ah, good idea 💡 Here the same within a single function:
Copy code
fun DocumentFile.walk(): Sequence<DocumentFile> {
  return sequence {
    suspend fun SequenceScope<DocumentFile>.walk(file: DocumentFile) {
      yield(file)
      if (file.isDirectory) {
        file.listFiles().forEach {
          walk(it)
        }
      }
    }
    walk(this@walk)
  }
}
7 Views