mjbsgll
mjbsgll

Reputation: 742

Scala: array.toList vs array.to[List]

I am wondering what is the difference between .toList vs .to[List] in arrays. I made this test in the spark-shell and there is no difference in the result, but I don't know what is better to use. Any comments?

scala> val l = Array(1, 2, 3).toList
l: List[Int] = List(1, 2, 3)

scala> val l = Array(1, 2, 3).to[List]
l: List[Int] = List(1, 2, 3)

Upvotes: 3

Views: 690

Answers (1)

Henrik
Henrik

Reputation: 452

Adding to Luis' comment, the to[List] is (as Luis mentioned) actually using a factory parameter to construct the list. However, the linked source is only valid from Scala 2.13+, after the collections overhaul. The syntax you use wouldn't work in Scala 2.13, instead you would have to write .to(List), explicitly passing the factory argument. In previous Scala versions, the method looked like this. The CanBuildFrom is essentially a factory passed as an implicit parameter.

The reason this method exists is that it is generic beyond collections in the standard library (and you don't have to define every single possible transformation as a separate method). You can use another collections library (e.g. Breeze), and either construct a factory or use an included one, and use the to(factory) method. You can also use it in generic functions where you take the factory as a parameter and just pass it on to the conversion method, for example something like:

def mapAndConvert[A, B, C](list: List[A], f: A => B, factory: Factory[B, C]): C[B] =
  list.map(f).to(factory)

In this example I don't need to know what collection C is, yet I can still return one with ease.

Upvotes: 2

Related Questions