Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

an idiomatic way to initialize a Scala ArrayBuffer?

Tags:

scala

I would like to initialize an ArrayBuffer with value -1 in indexes 0 through 99. Is there a simple, idiomatic way to do so?

This works, but it's a bit crufty:

val a = new ArrayBuffer&#91;Int&#93;()<br>
a.appendAll(Nil.padTo(100, -1))

I'd like to see something more like this:

val a = ArrayBuffer(List(-1) * 100)
like image 612
Johan Larson Avatar asked Jul 21 '12 17:07

Johan Larson


People also ask

What is the difference between Array and ArrayBuffer in Scala?

Arrays -- An array is a data structure which stores a collection of elements of the same type. Arrays have a fixed size. ArrayBuffer -- An ArrayBuffer is very similar to an array, except it can grow in size after it has been initialized.

Are Arrays mutable Scala?

Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size can't change.


1 Answers

collection.mutable.ArrayBuffer.fill(100)(-1)
like image 87
0__ Avatar answered Oct 09 '22 08:10

0__