How to create an infinitely long sequence in Kotlin

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

generateSequence(1, Int::inc)

if you're into the whole brevity thing.


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()

val sequence = generateSequence(1) { it + 1 }
val taken = sequence.take(5);
taken.forEach { println(it) }

This is not really infinite, though: it will overflow when Integer.MAX_VALUE is reached.

Tags:

Kotlin