3

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?

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This question came up because I saw this in a piece of code: def fun(ar: Array[Long]) = ar.toArray.combinations(3).[other ops] Does is make any sense in this concept? ar will always be of type Array[Long], correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.