3

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)
2
  • 9
    If you check the source, you will see they are equivalent. to[Coll] get the factory of Coll and pass this as an argument. - toList does the same, but explicitly using the Factory of List. - I would just use toList it reads better (for me) and will save you one indirection call. But in the end, they are the same. Commented Aug 15, 2019 at 15:13
  • 4
    @LuisMiguelMejíaSuárez I suggest write this as an answer Commented Aug 15, 2019 at 15:47

1 Answer 1

2

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.

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

Comments

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.