Koala3
Koala3

Reputation: 2335

How to make an ArrayBuffer of ArrayBuffer

I want a two-dimensional array of ArrayBuffer

Something like this:

var myRowOfStrings = new ArrayBuffer[String]
val myArrayOfRows = new ArrayBuffer[ArrayBuffer] // To store many ArrayBuffer[String]

But the Scala compiler doesn't like the second declaration:

scala> val myArrayOfRows = new ArrayBuffer[ArrayBuffer]
<console>:8: error: class ArrayBuffer takes type parameters
       val myArrayOfRows = new ArrayBuffer[ArrayBuffer]
                                       ^

Have I got the syntax wrong?

Or is an ArrayBuffer of ArrayBuffer not possible?

Upvotes: 2

Views: 4506

Answers (2)

kevin_theinfinityfund
kevin_theinfinityfund

Reputation: 2157

Import ArrayBuffer before applying it:

import scala.collection.mutable.ArrayBuffer
var e = ArrayBuffer("a", "b", "c")
scala> e: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(a, b, c)

Upvotes: 0

Kyle
Kyle

Reputation: 22258

ArrayBuffer objects require a type. It says so in the error message.

You need to tell the compiler what type of ArrayBuffer you want.

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val myArrayOfRows = new ArrayBuffer[ArrayBuffer[String]]
myArrayOfRows: scala.collection.mutable.ArrayBuffer[scala.collection.mutable.ArrayBuffer[String]] = ArrayBuffer()

Consider doing this if its easier.

type Row = ArrayBuffer[String]
var myRowOfStrings = new Row
val myArrayOfRows = new ArrayBuffer[Row]

Upvotes: 11

Related Questions