marisbest2
marisbest2

Reputation: 1356

Scala Parallel Seq not confroming to Seq

I'm relatively new to Scala but I think I understand its type system and parallel collections and I can't understand this error:

I have a function

def myFun(a : Seq[MyType], b : OtherType) : Seq[MyType] = {
    val parA = a.par
    def update(q : OtherType)(x : MyType) : MyType = x.updated(q)
    parA.map(update(b))

I get an error that says

Error:(63, 18) type mismatch;
 found   : scala.collection.parallel.ParSeq[MyType]
 required: Seq[MyType]
    parA.map(update(b))
                 ^ 

If ParSeq is a subtype of Seq then why doesn't this work?

(As I was writing this I realized that to fix it I can call the .seq method on the result, but why do I have to? and what's the difference between .toSeq which the IDE tells me is redundant and .seq which seems to have worked)

Upvotes: 2

Views: 3252

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

If ParSeq is a sub-type of Seq then why doesn't this work?

It isn't. ParSeq is a sub-type of GenSeq, which is not the same thing. The difference is that when you have a Seq, you expect all operations to happen in sequence, but with ParSeq, that is not necessarily the case!

If I have:

Seq(1, 2, 3, 4, 5) foreach println

I expect the elements to be printed in the order they are presented every time. ParSeq cannot guarantee that:

scala> ParSeq(1, 2, 3, 4, 5) foreach println
2
1
3
4
5

Therefore, if I were expecting a Seq, and instead got a ParSeq that had the above behavior, that could cause some nasty bugs. If you don't care about that and can handle both situations, ask for a GenSeq.

Upvotes: 4

A Spoty Spot
A Spoty Spot

Reputation: 746

I'm lookiing at the docs and can't see where it says ParSeq extends Seq, am I missing something?

Also as for the second part of the question: toSeq returns a ParSeq and seq returns a Seq. To be clear:

val x: ParSeq[Int] = Seq(1,2,3).par
val y: ParSeq[Int] = x.toSeq
val z: Seq[Int] = x.seq

Since the .toSeq doesn't 'do anything' your IDE is saying its redundant.

Upvotes: 9

Related Questions