Kotlin `IntRange`s don't hold any values in memory...
# announcements
m
Kotlin `IntRange`s don't hold any values in memory by themselves, is that right? I'm asking because my experience tells me they should be lazy, yet they are not `Sequence`s, so it's possible to get one from with
asSequence()
instead. And something like a direct
map
gives you a list. But I would still assume a range object doesn't contain anything, simply because "it makes sense" in my head.
Copy code
>>> (0..4).asSequence()
res0: kotlin.sequences.Sequence<kotlin.Int> = kotlin.collections.CollectionsKt___CollectionsKt$asSequence$$inlined$Sequence$1@7bafb922
>>> (0..4).map { it * 2 }
res1: kotlin.collections.List<kotlin.Int> = [0, 2, 4, 6, 8]
So what's in an
IntRange
before applying anything? (no
asSequence()
) for example
val myRange = 0..4
n
I haven't looked but I would assume than IntRange is simply its own type of object
that supports both iteration, and
in
and probably only stores the end points
(so, yes, it would be lazy)
okay, let me rephrase
its lazy in the sense that its not storing the whole list of values on it
but when you do chain operations on it (via e.g. map) it does things eagerly
If you just follow IntRange's parents in the docs this is pretty easy to figure out
it eventually inherits from Iterable, not Sequence
n
IntRange's are indeed stateless, and depending on how you construct them (e.g.
for (i in 1..4)
) may even get compiled away.
m
but when you do chain operations on it (via e.g. map) it does things eagerly
thanks, this is exactly what I meant. I'm glad I didn't need to give extra information to communicate the idea properly
n
Yeah. Remember that things like
map
, are simply generic extension functions. There's one
map
for sequences, which is lazy, and one for iterables, which isn't.
So to figure out which map you're calling, you just need to figure out which base class you have.
m
(e.g. 
for (i in 1..4)
) may even get compiled away.
ah yes, I saw that in the bytecode before. Well done compiler, well done. That's why I mentioned
IntRange
specifically