Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy list in kotlin?

Tags:

kotlin

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
like image 964
loloof64 Avatar asked Oct 26 '14 11:10

loloof64


People also ask

What is by lazy in Kotlin?

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.

Is Kotlin lazy evaluation?

Some functional languages provide a lazy (non-strict) evaluation mode. Kotlin, by default, uses an eager (strict) evaluation.

How do you declare lazy in Kotlin?

* 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.

Is Kotlin lazy thread safe?

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.


1 Answers

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?

like image 194
Andrey Breslav Avatar answered Oct 19 '22 02:10

Andrey Breslav