score:3

Accepted answer

For Scala 2.13 this would be the most general form.

import me.tongfei.progressbar.ProgressBar

def iterationModule[A](items: IterableOnce[A], f: A => Any): Unit = {
  val (it, pb) =
    if (items.knowSize != -1)
      items.iterator -> new ProgressBar("Test", items.knowSize)
    else {
      val (iter1, iter2) = items.iterator.split
      iter1 -> new ProgressBar("Test", iter2.size)
    }

  it.foreach { x =>
    f(x)
    pb.step()
  }
}

Note: most of the changes are just to make the code more generic, but the general idea is just to create a function that wraps both the original function and the call to the ProgressBar.


Edit

A simplified solution for 2.11

def iterationModule[A](items: Seq[A], parallel: Boolean = false)
                      (f: A => Any): Unit = {
  val pb = new ProgressBar("test", items.size)

  val it = if (parallel) {
    items.iterator.par
  } else {
    items.iterator
  }

  it.foreach { a =>
    f(a)
    pb.step()
  }
}

Related Query

More Query from same tag