SamTebbs33 SamTebbs33 - 4 months ago 27
Scala Question

Inserting value into MutableList

I would like to insert a value into a specific index in a scala

which will push successive elements one index along (much like the
java.util.List.add(index, element)
method). I tried using the
method and it compiled but annoyingly I got an
exception at runtime.

I wrote the below method (where
is the
instance) but as you can see it requires a lot of what I deem unnecessary conversion steps. Is there a built-in/faster way of doing it?

def insert(idx: Int, element: String): Unit ={
val newList = new scala.collection.mutable.MutableList[String]()
for(i <- 0 until idx) newList += mList(i)
newList += element
for(i <- idx until content.size) newList += mList(i)
mList = newList

Psuedocode example:

mList = ["a", "f", "x", "e"]
insert(2, "z")
// mList is now ["a", "f", "z", "x", "e"]

I have seen answers on here that apply to immutable lists, but none that apply to mutable lists.


Here is an alternative way of inserting an element in the mutable list:

val ls = MutableList(1,2,3,4) 

val pair = ls.splitAt(1) // split it at the appropriate index into two lists.

pair._1 ++ MutableList(20) ++ pair._2 // MutableList(1, 20, 2, 3, 4)