0

Reading the doc(https://www.scala-lang.org/api/2.12.4/scala/collection/immutable/Vector.html) it does not appear possible to set the max number of elements in a Vector, when the max number of elements is reached then elements are discarded first in, first out.

To achieve this I could do something like:

var a = Vector[Double]
val MAX_ELEMENTS = 1000
def addElement(element: Double) = {
    if(a.size() == MAX_ELEMENTS){
        a = a.dropRight(a.length())
    }
    a = a :+ element
}

But this seems very inefficient. Is there more elegant method to maintain a constant number of elements in a Vector, when the Vector reaches a pre-determined size?

Update: Using a Queue achieves what I want:

This is the approach I toke with extending Scala's standard mutable.Queue class.

class LimitedQueue[A](maxSize: Int) extends mutable.Queue[A] {
  override def +=(elem: A): this.type = {
    if (length >= maxSize) dequeue()
    appendElem(elem);
    this
  }
}

And simple use-case

var q2 = new LimitedQueue[Int](2)
q2 += 1
q2 += 2
q2 += 3
q2 += 4
q2 += 5

q2.foreach { n =>
  println(n)
}

from Maximum Length for scala queue

blue-sky
  • 51,962
  • 152
  • 427
  • 752

0 Answers0