Factory .ofDim[T](size: Int) on mutable.ArrayBuffer

Hi, not sure if I should post this here or file a bug.

I propose a new factory method on mutable.ArrayBuffer, ofDim

It would work the same was as Array::ofDim. I don’t think there’s a need for Array’s multi-dimensional overloads, since those are uncommon.

There is currently a constructor we can use, but with Scala 3 adding automatic apply methods, having to use new just for ArrayBuffer makes it stick out in my code.

are you trying to specify the initial size? because you can also call sizeHint. ofDim seems odd to me as an ArrayBuffer can grow, and also does not currently respect the exact size


Any particular reason why this method is proposed just for mutable.ArrayBuffer, rather than mutable.Buffer? ArrayBuffer is meant to be just one implementation for Buffer, so you would expect the API to be the same.

As @NthPortal is alluding to, Array is a fixed-size collection, while Buffer is designed to change size, so they are not analogous.


Had no idea that method existed. It might be even faster than the constructor (after initialization) since the implementation maintains the backing array size as a power of 2.

Thanks for the help removing the only new I’ve written in the last week!

Probably the wrong place for this, but the only new I’m writing is in:

throw new NoSuchElementException(...)

It’s somewhat confusing because:

throw AssertionError(...)

works like a charm, and they’re both Java classes anyway.

That’s because NoSuchElementException is defined as a type alias in the scala package:

type NoSuchElementException          = java.util.NoSuchElementException

and you don’t get the creator application on type aliases, see https://github.com/lampepfl/dotty/pull/10784#issuecomment-748631079 and https://github.com/lampepfl/dotty/issues/10862

By contrast, AssertionError is not a type alias but included in the default import of java.lang._

A workaround is to import java.util.NoSuchElementException

If you actually do want an ArrayBuffer filled with some default value, you can use Arraybuffer.fill.