Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't toList and friends deprecated?

Tags:

scala

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?

like image 596
AmigoNico Avatar asked Mar 04 '13 18:03

AmigoNico


2 Answers

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.

like image 163
Samuel Tardieu Avatar answered Oct 20 '22 14:10

Samuel Tardieu


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)
like image 23
BeniBela Avatar answered Oct 20 '22 13:10

BeniBela