is there any way to get current iteration using ge...
# announcements
x
is there any way to get current iteration using generateSequence?
so if you wanted the sequence to be (1, 2, 3, 4, 5) based on iteration value
(i mean of course you can declare var 0 outside the generator and ++ it but im wondering if there is an idiomatic way)
g
I believe
Copy code
generateSequence(0){it + 1}
will do it
x
you're right for int, but what if you want to return something different? lets say you want to use the current iteration as part of something else, like
Copy code
generateSequence(0){
  if (fooCondition) "the number is ${it}"
  else null
}
it wouldnt work, correct?
g
I think you would likely want to do that kind of logic in a block of code that consumes from the sequence, not from the sequence generation itself. So for the example you give you may want to append a
.forEach
or a
.map
Copy code
generateSequence(0){it + 1}
  .map { 
    if (fooCondition) "the number is ${it}"
  else null 
}
actually nevermind, that example with
.map
is functionally equivalent to yours.
.forEach
would actually cause the sequence to start iterating, and is likely what you want
x
but that would generate an infinite sequence, no?
g
yes, unless you had a return statement
x
i think my best shot is just using a normal counter as ugly as it is, because my use case is a bit more specific:
Copy code
generateSequence(0){
  if (foo * it > bar) baz
  else null
}
where baz is not an int of course
g
hmm interesting. Another suggestion to help avoid any nulls and the counter:
Copy code
generateSequence(0) { it + 1 }
  .takeWhile { it * foo > bar }
  .map { baz }
x
i love that one
thank you!
👍 1