Assuming I have a (what I assume is mutable by default) Array[String]
How in Scala can I simply remove the nth element?
No simple method seems to be available.
Want Something like (I made this up):
def dropEle(n: Int): Array[T]
Selects all elements except the nth one.
n
the subscript of the element to drop from this Array.
Returns an Array consisting of all elements of this Array except the
nth element, or else the complete Array, if this Array has less than
n elements.
Many thanks.
That is what views are for.
scala> implicit class Foo[T](as: Array[T]) {
| def dropping(i: Int) = as.view.take(i) ++ as.view.drop(i+1)
| }
defined class Foo
scala> (1 to 10 toArray) dropping 3
warning: there were 1 feature warning(s); re-run with -feature for details
res9: scala.collection.SeqView[Int,Array[Int]] = SeqViewSA(...)
scala> .toList
res10: List[Int] = List(1, 2, 3, 5, 6, 7, 8, 9, 10)
The problem is with the semi-mutable collection you chose, since an Array's elements may be mutated but its size cannot be changed. You really want a Buffer which already provides a "remove(index)" method.
Assuming you already have an Array, you can easily convert it to and from a Buffer in order to perform this operation
def remove(a: Array[String], i: index): Array[String] = {
val b = a.toBuffer
b.remove(i)
b.toArray
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With