How to create a Scala ArrayBuffer (syntax)

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.