Hello. I need to write
a function to copy (with my algorithm) traversable of arbitrary
type. This function should return the same type
of traversable that passed to
the input. I'm trying to
do so:
import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom
trait DeepCopy[A] {
def deepCopy: A
def deepCopyAs[B]: B = deepCopy.asInstanceOf[B]
}
object DeepCopy {
def copyTr[A, T[X] <: Traversable[X]](seq:
T[A])(implicit cf: CanBuildFrom[T[A], A, T[A]]): T[A] =
seq.map[A, T[A]] {
case x: DeepCopy[_] => x.deepCopyAs[A]
case x => x
}(cf)
}
DeepCopy.copyTr(Vector(1, 2, 3))
and I get error:
scala> :pa test.scala
Pasting file test.scala...
<console>:19: error: type mismatch;
found :
scala.collection.generic.CanBuildFrom[T[A],A,T[A]]
required:
scala.collection.generic.CanBuildFrom[Traversable[A],A,T[A]]
}(cf)
^
If I change code as follows:
import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom
trait DeepCopy[A] {
def deepCopy: A
def deepCopyAs[B]: B = deepCopy.asInstanceOf[B]
}
object DeepCopy {
def copyTr[A, T[X] <: Traversable[X]](seq:
T[A])(implicit cf: CanBuildFrom[Traversable[A], A,
T[A]]): T[A] = seq.map[A, T[A]] {
case x: DeepCopy[_] => x.deepCopyAs[A]
case x => x
}(cf)
}
DeepCopy.copyTr(Vector(1, 2, 3))
then I get another error:
scala> :pa test.scala
Pasting file test.scala...
<console>:24: error: Cannot construct a
collection of type scala.collection.immutable.Vector[Int] with
elements of type Int based on a collection of type
Traversable[Int].
DeepCopy.copyTr(Vector(1, 2, 3))
^
What am i doing wrong?