0

I am doing some prototyping and I need a quick way to speed up some algorithm. So I was looking at Scala Parallel Collections. Without going into the details of why I need to use foreach, can someone shed light on why the following crashes (just an example):

List(1,2,3,4).combinations(2).asParIterable.foreach(_ => println("foo"))

java.lang.ClassCastException: scala.collection.SeqLike$CombinationsItr cannot be 
  cast to scala.collection.parallel.ParIterable
at scala.collection.parallel.package$$anon$2.asParIterable(package.scala:70)

(Scala is 2.10.3)


Or in other words: How can I parallelize an iterator?

0__
  • 66,707
  • 21
  • 171
  • 266

1 Answers1

3

You can't parallelize an iterator; you can turn it into an iterable and parallelize that:

List(1,2,3,4).combinations(2).toSeq.par.foreach(_ => println("foo"))

I am not sure if toIterable instead of toSeq will work as well. However, if you only need foreach,

iterator.foreach(_ => Future(println("foo")))

should work.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Ok thanks that works, also `toParArray`. I was hoping that I don't need to keep all the permutations (which can be a lot in my actual case) in memory, but no `OutOfMemoryError` yet... – 0__ Feb 20 '14 at 18:35