Grayden Hormes
Grayden Hormes

Reputation: 875

Kotlin infinite sequences with iterator function

I am confused about how to create an infinite sequence in Kotlin to use for lazy evaluation.

In Java:

IntStream.iterate(0, i -> i + 2)
     .limit(100)
     .forEach(System.out::println);

but sequences seem much more confusing then Java streams. The sequence constructor is very confusing the doc for it says:

/**
 * Given an [iterator] function constructs a [Sequence] that returns values through the [Iterator]
 * provided by that function.
 * The values are evaluated lazily, and the sequence is potentially infinite.
 */

but I don't know what it means by an iterator function or how to make one.

Sequence { iterator(arrayOf<Int>()) }
        .forEach { print(it) }

I have this which compiles but obviously doesn't print anything. I don't think my iterator function makes any sense. It wants a function that takes no arguments and returns an iterator, which isn't like the Java .iterate function at all. Iterator happens to have a constructor that takes an array, which would make sense if I had a data set to work with in an array but I don't. I want to be working with an infinite sequence.

There is no .limit, so I previously tried to add a .reduce but the arguments for .reduce were even more confusing. I think there should be a .toList but I knew it wasn't working so I didn't try it.

If someone would show me how to implement the above Java code in Kotlin it would help a lot.

Upvotes: 13

Views: 9930

Answers (1)

AndroidEx
AndroidEx

Reputation: 15824

You can use generateSequence factory method:

generateSequence(0) { it + 2 }.forEach { println(it) }

or for the limited case:

generateSequence(0) { it + 2 }.take(100).forEach { println(it) }

Upvotes: 35

Related Questions