what is the ideomatic way to get a copy of an Arra...
# getting-started
f
what is the ideomatic way to get a copy of an Array without element
n
?
e
Copy code
val array = arrayOf(1, 2, 3)
val slice = array.dropLast(1)
f
I don't think so @Egor Okhterov:
Returns a list containing all elements except last n elements.
e
array.dropLast(n)
f
n
as in any index, not necessesarily the last one
e
n is the number of elements
s
This isn’t a great operation for a Kotlin array - elements aren’t linked so repeated scanning will have to occur to get your result
you can do this:
Copy code
inline fun <reified T> Array<T>.withoutIndex(index: Int): Array<T> =
    (dropLast(index + 1) + drop(index + 1)).toTypedArray()
but if you need to arbitrarily drop elements within this collection a lot, consider a LinkedList instead?
f
n is the number of elements
bold claim
😂 3
e
Oh, you mean without
n'th
element
👍 2
Usually people use the other variable for that, so I was confused 😃
f
No worries, I noticed my question wasn't crystal clear
d
An optimized version: https://pl.kotl.in/90_QAXN2D
👏 1
s
this might be a hair better?
Copy code
inline fun <reified T> Array<T>.withoutIndex(index: Int): Array<T> =
    sliceArray(0 until index) + sliceArray((index + 1) until size)
d
That's 3 array copy operations
s
sorry, didn’t mean relative to your suggestion @diesieben07
d
And it's allocating 3 new arrays
s
just iterating on my last suggestion
f
Thanks @diesieben07 and @Shawn super helpful, I'll try your suggestions. 📗
👍 1
e
Copy code
arr.filterIndexed { i, _ -> i != n }
2
👍 2
t
If you are using arrays instead of lists for performance reasons, you should stick with
System.arraycopy
(JVM-only).
d
(Which is what
copyInto
uses)
👍 1