I am trying to implement an implicit function mapMetered
that wraps map
and functions exactly like it in terms of returning the correct type. I tried this:
implicit class MeteredGenTraversablePimp[T, C[T] <: GenTraversable[T]](trav: C[T]) {
def foreachMetered(m: Meter)(f: T => Unit) =
m.foreach(trav)(f)
def mapMetered[B, That](m: Meter)(f: (T) => B)(
implicit bf: CanBuildFrom[C[T], B, That]
): That = {
m.start()
try {
trav.map { x =>
val z = f(x)
m.item_processed()
z
} (bf)
} finally { m.finish() }
}
}
But when I try this I get an error:
[info] Compiling 1 Scala source to /Users/benwing/devel/textgrounder/target/classes...
[error] /Users/benwing/devel/textgrounder/src/main/scala/opennlp/textgrounder/util/metering.scala:223: type mismatch;
[error] found : scala.collection.generic.CanBuildFrom[C[T],B,That]
[error] required: scala.collection.generic.CanBuildFrom[scala.collection.GenTraversable[T],B,That]
[error] } (bf)
[error] ^
[error] one error found
There are similar Stack Overflow questions, including one from Daniel Sobral who suggests writing (trav: C[T] with GenTraversableLike[T])
but this doesn't fix the problem.