Reputation: 6593
I'm looking for something like
val allInts = (1..).asSequence()
so I could, for example
allInts.take(5)
Upvotes: 15
Views: 4932
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
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
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
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