https://kotlinlang.org logo
Title
d

df

04/25/2019, 9:39 AM
is there a more idiomatic way in kotlin to write sth. like this?
while (true) {
    val rows = repo.findAll(page)

    if (rows.isEmpty()) {
        break
    }

    doSomething(rows)
}
p

pablisco

04/25/2019, 9:42 AM
sequence { yield(repo.findAll(page)) }
  .filter { it.isNotEmpty() }
  .forEach(::doSomething)
🤔
d

diesieben07

04/25/2019, 9:42 AM
You could do
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

pablisco

04/25/2019, 9:42 AM
Ah! break, not continue 🤔
generateSequence { 
  repo.findAll(page).takeIf { it.isNotEmpty() } 
}.forEach(::doSomething)
or
generateSequence { 
  repo.findAll(page).takeUnless { it.isEmpty() } 
}.forEach(::doSomething)
d

df

04/25/2019, 9:45 AM
@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

diesieben07

04/25/2019, 9:45 AM
No, my code was supposed to go inside the
while(true)
loop
I just refactored the is-empty-then-break part of it
d

df

04/25/2019, 9:45 AM
ah
need to read up a few methods, thanks so far
d

Dominaezzz

04/25/2019, 11:56 AM
generateSequence { repo.findAll(page) }
  .takeWhile { it.isNotEmpty() }
  .forEach(::doSomething)
👍 2