I am trying to write a generic fill method, and following is what I have come up with so far:
scala> import collection.generic.{GenericTraversableTemplate => GTT}
import collection.generic.{GenericTraversableTemplate=>GTT}
scala> import collection.generic.{TraversableFactory => TF}
import collection.generic.{TraversableFactory=>TF}
scala> def fill[A, CC[X] <: Traversable[X] with GTT[X, CC]]
| (n: Int)(elem: => A)(tf: TF[CC]) = tf.fill(n)(elem)
fill: [A, CC[X] <: Traversable[X] with scala.collection.generic.GenericTraversab
leTemplate[X,CC]](n: Int)(elem: => A)(tf: scala.collection.generic.TraversableFa
ctory[CC])CC[A]
scala> fill(3)('d')(List)
res42: List[Char] = List(d, d, d)
This works with all traversable collections except arrays. How do I make this code work with arrays?
If you don’t mind creating an extra object, there’s
It doesn’t get around objection (2), but the usage is nice: