0

What is the best way of adding to a specific index of a list in scala?

This is what I have tried:

case class Level(price: Double) 

case class Order(levels: Seq[Level] = Seq())

def process(order: Order) {
    orderBook.levels.updated(0, Level(0.0))
}

I was hoping to insert into position zero the new Level but it just throws java.lang.IndexOutOfBoundsException: 0 . What is the best way of handling this? Is there a better data type other than Seq which should be used for keeping track of indexes in a list?

1

1 Answer 1

2

Is there a better data type other than Seq which should be used for keeping track of indexes in a list?

Yes, a Vector[T] is recommended when you want random access into the underlying collection:

scala> val vector = Vector(1,2,3)
vector: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)

scala> vector.updated(0, 5)
res3: scala.collection.immutable.Vector[Int] = Vector(5, 2, 3)

Note that a Vector will also through an IndexOutOfBoundsException when you try to insert data into an empty vector. A good way of appending and prepending data is using :+ and :+, respectively:

scala> val vec = Vector[Int]()
vec: scala.collection.immutable.Vector[Int] = Vector()

scala> vec :+ 1 :+ 2
res7: scala.collection.immutable.Vector[Int] = Vector(1, 2)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! How do you use the newly updated Vector to overwrite the existing one stored in Order? How about if you want to insert (not update) into the Vector?
@maloney You can use a var vector field and keep updating it. Or, you can choose another mutable collection as needed. Insert is as I've shown using :+ and +:.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.