Home > Software design >  How to create an immutable array within a mutable array in scala?
How to create an immutable array within a mutable array in scala?

Time:11-11

So I am trying to create an immutable array of size 10 within a mutable array in scala. In this immutable array I want to store key, value pairs. so far I have this mutable array:

val array1 = mutable.ArrayBuffer[Option[IndexedSeq[(A,B)]]]()

Now to create an immutable buffer in array1 would I just do:

array1(0) = immutable.ArrayBuffer[](10)

I am confused on what would go within the brackets of the immutable buffer for the type.

CodePudding user response:

There is no immutable.ArrayBuffer.  ArrayBuffer is mutable.

Trait IndexedSeq can correspond to both immutable and mutable collections, so you have options what to use as your inner elements:

type A = Int
type B = Int

val array1 = mutable.ArrayBuffer[Option[IndexedSeq[(A,B)]]]()

// Adds immutable Vector
array1  = Some(IndexedSeq[(A, B)]( (1,2), (3,4) ))

// Adds mutable ArrayBuffer
array1  = Some(ArrayBuffer[(A, B)]( (1,2), (3,4) ))

Note, since your inner element is Option[IndexedSeq[...]], you need to wrap the elements you are adding in Some.

  • Related