From time to time I find myself looking for an ext...
# stdlib
e
From time to time I find myself looking for an extension function to map from
Array<A>
to
Array<B>
Copy code
myArray.mapToArray { ... }
It's strange not having it in the standard library.
j
It's actually rare to use arrays in Kotlin. They are usually reserved for low-level data structure implementations. That's why we don't get a lot of functions in the stdlib around them.
What do you use arrays for, in your case?
e
Indeed I am working on a low level library, a TCP protocol implementation where I need to avoid dynamic data structures.
j
Then you probably don't want to create new arrays unnecessarily with functions like
map
, right?
e
Basically what I want to avoid is passing by a
List<T>
and having to call
toTypedArray()
I don't want to allocate that list.
And it feels off to have to use something like
Copy code
val newArray = Array(myArray.size) {
  val e = myArray[it]
  ...
}
j
I see your point. To be fair it doesn't feel off (to me) to use this kind of function in low level stuff
e
It's not really bad, but the index access is what worries me, very error prone. A
mapToArray
function wouldn't need to expose the index.
j
Yes I see, well of course it's kotlin, so you can write your own extension to abstract this away 🙂
The question is whether it's worth adding these things to the stdlib. I don't have the answer to that, but my gut feeling tells me that this would encourage the use of arrays over list, which we probably don't want.
e
There is also another solution
Copy code
val newArray = Array<NewType>(myArray.size)
myArray.mapTo(newArray) { ... }
But still, two steps instead of one and less code clarity.
so you can write your own extension to abstract this away
Will definitely do that. I see I do this in more than 20 places, so extracting is good.
e
mapTo
(and other
*to
functions) return the target, so it can be done in one step
if you're low-level enough to be using Arrays though, allocating new ones should not be something that happens automatically IMO
e
Ah wait, I actually wrote a piece of code that doesn't work
Copy code
val newArray = Array<NewType>(myArray.size)
myArray.mapTo(newArray) { ... }
That can't work as
Array<NewType>(myArray.size)
requires an initializer for each element. Also
mapTo
doesn't accept arrays.
e
that if you're working low-level, you are probably concerned about recycling arrays anyway
and you can totally add your own overloads, there's just about a bazillion of them