Is it safe to assume that collection transformatio...
# announcements
d
Is it safe to assume that collection transformation functions like
map
return Lists whose
get
method is O(1)? If so, is that documented?
s
well,
map
is defined as an extension method to a number of collection types
the
map
you’re referring to is likely
inline fun <T, R> Iterable<T>.map()
d
Right, that one.
c
I believe the default implementation is to map the results to an
ArrayList
, which gets mapped to the underlying platform-specific equivalent. I don’t think it’s specifically documented, but it’s easy enough to see by looking at the source
s
which does return a
List
, but neither the Iterable nor List interfaces make any guarantee as to underlying access complexities
d
I can read the source and I know what it does. A colleague is wondering if it's ok to rely on this if you need the return value to be O(1)
s
it really depends on what counts as “good enough” as a guarantee in your situation
it’s my understanding that the language makes no guarantees as to what kind of
List
will be returned by that map function, but pragmatically speaking on the JVM it’s going to be
ArrayList
more likely than not
c
For a strict guarantee, you should probably use
mapTo(ArrayList())
instead.
👆 3
d
Hmm I guess you can add an extension function like
if (this is Random Access) this else ArrayList(this)
There's nothing like that in the stdlib right? Your suggestion is nice though it misses the capacity calculation from the stdlib version
(I'm kind of of the opinion that in the Java/Kotlin world, if a function returns a LinkedList of non constant size you really need to document that fact, but technically it's legal)
s
I’m not sure how your extension function would work in a general case - there is no
Random Access
interface or abstract type to match upon, but
(edit: apparently there is) sure, you could do something like that, and there isn’t a semantically-comparable function available in the stdlib to my knowledge
d
There is such an interface... Unless it's internal to the stdlib?
c
Generally, I wouldn’t rely upon constant-time access for anything in a List, regardless of the type. Usually, you’d use a Map for guarantees of random-access time-complexity.
Lists are for iterating, Maps are for random access
s
Would you care to enlighten me @David Glasser? I’m not familiar with the interface in question
s
oh wow, today I learned
d
Sure, but arrays are for random access by index if your data is usefully ordered!
☝️ 1
s
cool 👍
d
Me too!
The empty list class (which I don't think is public but is eg returned by listOf() implements it too
s
I suppose
new IndexOutOfBoundsException()
is a
O(1)
operation 🤔