pondermatic
pondermatic

Reputation: 6593

How to create an infinitely long sequence in Kotlin

I'm looking for something like

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

so I could, for example

allInts.take(5)

Upvotes: 15

Views: 4932

Answers (4)

dkb
dkb

Reputation: 4596

As mentioned in this answer, you would need a function which will generate someValue all the time sequence is invoked, this answer provides one of the implementation which will generate infinite many values. e.g. Characters from a String and you can write function as

var index = -1L
val seq = generateSequence {
  val length = "instructions".length
  "instructions"[(++index % length).toInt()].toString() //.toString() will convert char to String
}
.take(10000) // just for printing 10000 chars
seq.forEach { println(it) }

This will generate Strings and Heap space size is the limiting factor.

Upvotes: 0

Michael
Michael

Reputation: 54735

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

Upvotes: 10

JB Nizet
JB Nizet

Reputation: 692281

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.

Upvotes: 19

BPS
BPS

Reputation: 1677

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

generateSequence(1, Int::inc)

if you're into the whole brevity thing.

Upvotes: 10

Related Questions