is there a more idiomatic way in kotlin to write s...
# getting-started
d
is there a more idiomatic way in kotlin to write sth. like this?
Copy code
while (true) {
    val rows = repo.findAll(page)

    if (rows.isEmpty()) {
        break
    }

    doSomething(rows)
}
p
Copy code
sequence { yield(repo.findAll(page)) }
  .filter { it.isNotEmpty() }
  .forEach(::doSomething)
🤔
d
You could do
Copy code
val rows = logRepository.findProcessable(page).takeUnless { it.isEmpty() } ?: break
doSomething(rows)
Which some might more "idiomatic", however personally I don't think an if statement is "not-idiomatic" (whatever that means). Everyone understands if statements so there is nothing wrong with your code.
p
Ah! break, not continue 🤔
Copy code
generateSequence { 
  repo.findAll(page).takeIf { it.isNotEmpty() } 
}.forEach(::doSomething)
or
Copy code
generateSequence { 
  repo.findAll(page).takeUnless { it.isEmpty() } 
}.forEach(::doSomething)
d
@diesieben07 your code would break the idea of processing one page at a time right? It would collect all rows and process them afterwards right?
d
No, my code was supposed to go inside the
while(true)
loop
I just refactored the is-empty-then-break part of it
d
ah
need to read up a few methods, thanks so far
d
Copy code
generateSequence { repo.findAll(page) }
  .takeWhile { it.isNotEmpty() }
  .forEach(::doSomething)
👍 2