Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an infinitely long sequence in Kotlin

Tags:

kotlin

I'm looking for something like

val allInts = (1..).asSequence()

so I could, for example

allInts.take(5)
like image 535
pondermatic Avatar asked May 03 '16 15:05

pondermatic


2 Answers

JB's answer is good but you could also go with

generateSequence(1, Int::inc)

if you're into the whole brevity thing.

like image 152
BPS Avatar answered Oct 26 '22 04:10

BPS


If you need an infinite sequence you should use the new sequence function:

val sequence = sequence {
  while (true) {
    yield(someValue())
  }
}

Previous answer

Use Int.MAX_VALUE as the upper bound. You cannot have an integer greater than Int.MAX_VALUE.

val allInts = (1..Int.MAX_VALUE).asSequence()
like image 29
Michael Avatar answered Oct 26 '22 04:10

Michael