Prior to version 2.10 of Scala sequence types had methods like toList
and toArray
for converting from one type to another. As of Scala 2.10 we have to[_]
, e.g. to[List]
, which appears to subsume toList
and friends and also give us the ability to convert to new types like Vector
and presumably even to our own collection types. And of course it gives you the ability to convert to a type which you know only as a type parameter, e.g. to[A]
-- nice!
But why weren't the old methods deprecated? Are they faster? Are there cases where toList
works but to[List]
does not? Should we prefer one over the other where both work?
toList
is implemented in TraversableOnce
as to[List]
, so there won't be any noticeable performance difference.
However, toArray
is (very slightly) more efficient than to[Array]
as the former allocates an array of the right size while the latter first creates an array and then sets the size hint (as it does for every target collection type). This should not make a difference in a real application unless you are converting data to arrays in a tight loop.
The old methods could easily be deprecated, and I bet they will in the future, but people are so used to them that deprecating them right away would probably make some people angry.
On issue seems to be that you cannot use to[] in postfix notation:
scala> Array(1,2) toList
res2: List[Int] = List(1, 2)
scala> Array(1,2) to[List]
<console>:1: error: ';' expected but '[' found.
Array(1,2) to[List]
scala> Array(1,2).to[List]
res3: List[Int] = List(1, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With