Is there an IterableFactory[Array]?

Is there something in the standard library that would have type IterableFactory[Array]? I have code that uses an IterableFactory[Seq] and then converts the result using toArray and I’m wondering if I could build the array directly instead.

Yes, Factory.arrayFactory.
It can’t be an IterableFactory since Array is not an Iterable, but the end result is the same.


If you really need an IterableFactory, you may use the one for ArraySeq and then use the unsafeArray inside of it.


You may also just use an ArrayBuilder, which may be more efficient, but I would assume Factory[Array] already uses that under the hood.


2 Likes

It’s just called array. It returns an array typed as Array[?], however, so you need to (unsafely) cast it. The reason it is that way is because it can’t create primitive arrays with generic operations, and it must support generic operations.

scala> val literal = collection.mutable.ArraySeq(1, 2, 3)
val literal: scala.collection.mutable.ArraySeq[Int] = ArraySeq(1, 2, 3)
                                                                                
scala> val literalClass = literal.array.getClass
val literalClass: Class[? <: Array[?]] = class [I
                                                                                
scala> val mapped = collection.mutable.ArraySeq("a", "bb", "ccc").map(_.length)
val mapped: scala.collection.mutable.ArraySeq[Int] = ArraySeq(1, 2, 3)
                                                                                
scala> val mappedClass = mapped.array.getClass
val mappedClass: Class[? <: Array[?]] = class [Ljava.lang.Object;
1 Like