By Alvin Alexander. Last updated: March 18, 2019
As a quick note, this is the syntax for creating a Scala ArrayBuffer
:
import scala.collection.mutable.ArrayBuffer val fruits = ArrayBuffer[String]() val ints = ArrayBuffer[Int]()
The key thing to know is that the keyword new
is not required before the ArrayBuffer
. (This is because ArrayBuffer
is either defined as a case class, or because it has an apply method defined. I haven’t looked at its source code to know which approach is taken.)
While I’m in the neighborhood, here are some other ways you can work with ArrayBuffer
:
val x = ArrayBuffer('a', 'b', 'c', 'd', 'e') val characters = ArrayBuffer[String]() characters += "Ben" characters += "Jerry" characters += "Dale"
For more examples of how to use ArrayBuffer
, see How to delete ArrayBuffer elements.