4 ms·
I can't seem to find anything on the Kotlin Github repo that implies code like this: ints.filter { i -> i > 0 }.map { i -> i*i } will use deferred executi
by edgyswingset 11y ago
I can't seem to find anything on the Kotlin Github repo that implies code like this:
ints.filter { i -> i > 0 }.map { i -> i*i }
will use deferred execution. Is this correct? If so, why?
- barrkel 11y agoThe type of 'filter' and 'map' should tell you whether they are eager or lazy. If they return something iterable and uncountable except by consuming, then they're probably lazy. If they return something array or collection-like, they're probably eager. I had a quick scan of the Kotlin repo, and I think it depends on the type that you start out with. The sequence stuff is lazy; the map stuff is eager.
- edgyswingset 11y agoLooking at the docs on Iterable, map and filter return List<T>, not another Iterable. I imagine this isn't a concern when you've got small data sets, but I wouldn't feel safe using this when performance is a concern.
- asdf1234 11y agoI haven't played with Kotlin in a while but if you want collection operations to be lazy you have to explicitly convert it to a sequence. So your example would be something like: ints.asSequence().filter { it > 0 }.map { it * it } and then you can convert it to a concrete collection type with toList, toHashSet, toArrayList etc.
- edgyswingset 11y agoThat's just baffling to me. Why would they advertise chaining together sequence operations like this as being LINQ-like (or like Clojure and other functional languages) when it's eager by default? What is gained by making these eager by default? It just seems like a poor choice to me. That's a shame, because I feel like it's otherwise a pretty well-designed language.
- djur 11y agoPlenty of functional languages do not have lazy sequences by default. Haskell does because the entire language is lazy by default, and Clojure does as a conscious design decision (one that is not shared by its Lisp, Smalltalk, Ruby, and ML influences). There are plenty of hardcore functional programmers who will argue that strict by default and lazy by choice is the preferable option. The reason Kotlin sequence operations aren't lazy by default is probably because Java collections aren't, and Kotlin code is going to spend a lot of time dealing with Java collections. And, frankly, it's always a tradeoff to implement lazy collections in a strict language -- people using them need to become intimately aware of exactly which operations are lazy and which are eager.