Bar
Bar

Reputation: 2826

Scala: Use case for Array.toArray?

Scala.Array includes a function toArray, as an implicit import from ArrayOps.

Are there any use cases for Array.toArray or will it always return a copy of the object?

Upvotes: 3

Views: 194

Answers (1)

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

ArrayOps inherits toArray from GenTraversableOnce (and a default implementation is provided in TraversableOnce)

In case of an Array it's pointless, but the method is there for all the other subclasses of GenTraversableOnce, like Map, List, Set and many others.

Analogously, Map inherits a pointless toMap method, List a toList, Set a toSet and so on.


In the specific case of toArray, the default implemention provided in the TraversableOnce trait is overridden by ArrayOps.

Calling toArray on an Array will return a new one only if the runtime class of the destination type is different, otherwise it will just cast the Array to the appropriate type and return the same instance.

So, generally speaking, calling toArray on an instance of Array is useless, although not significantly expensive.

Upvotes: 7

Related Questions