Scala: Yielding from one type of collection to another

Viewed 16590

Concerning the yield command in Scala and the following example:

val values = Set(1, 2, 3)
val results = for {v <- values} yield (v * 2)

  • Can anyone explain how Scala knows which type of collection to yield into? I know it is based on values, but how would I go about writing code that replicates yield?
  • Is there any way for me to change the type of the collection to yield into? In the example I want results to be of type List instead of Set.
  • Failing this, what is the best way to convert from one collection to another? I know about _:*, but as a Set is not a Seq this does not work. The best I could find thus far is val listResults = List() ++ results.

    Ps. I know the example does not following the recommended functional way (which would be to use map), but it is just an example.

  • 3 Answers
    Related