How can I achieve in a simple way a Lazy List in Kotlin? (For example, integers lazy list). I've been seeking official documentation, I've been googling for that without consistent results. Maybe the best tutorial I've found is here, but I wonder if there is a more Kotlin idiomatic way for doing that.
I've found the following on Kotlin's official blog, though I was unable to get an item, with integers[3] for example
var i = 0
integers = iterate{i++}
integers[3] // does not work
integers drop 3 // works
Lazy is mainly used when you want to access some read-only property because the same object is accessed throughout. That's it for this blog.
Some functional languages provide a lazy (non-strict) evaluation mode. Kotlin, by default, uses an eager (strict) evaluation.
* To create an instance of [Lazy] use the [lazy] function. * Gets the lazily initialized value of the current Lazy instance. * Once the value was initialized it must not change during the rest of lifetime of this Lazy instance.
It is lazy and thread-safe, it initializes upon first call, much as Java's static initializers. You can declare an object at top level or inside a class or another object.
As you correctly observed, sequenceOf
(streamOf()
in older versions) is the way to get a lazy stream of numbers. Unlike Haskell, there's no such thing as a lazy list in Kotlin's standard library, and for a good reason: the primary meaning of "list" in Haskell world and Java world is different. In Haskell, a list is primarily a linked list, a pair of head and tail, and the main operation is taking a head of such a list, which is straightforward to efficiently implement lazily. In Kotlin/Java, list is a data structure with random access to its elements, and the main operation is get(int)
, which can be implemented lazily, of course, but its performance will often be surprising for the user.
So, Kotlin uses streams for laziness, because they are good when it comes to the main use cases of lazy collections: iteration, filtering, mapping, and random access is unlikely to be encountered very often.
As you, again, correctly observe, drop
lets you access elements by index, which makes the performance implications more explicit in the code.
BTW, what is your use case for lazy lists?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With