I have a generic method that should return a collection of the same type as input:
def removeN[A, C <: Seq[A]](s: C, n: Int): C = {
s.take(n) ++ s.drop(n + 1) // Sample operation
}
But this code does not compile:
Error:(34, 15) type mismatch; found : Seq[A] required: C s.take(n) ++ s.drop(n + 1)
- How is this possible when
Cclearly stands forSeq[A]? Does it mean that this kind of concatenation always return an instance of parent typeSeq[A], not a subtypeC? Could my code be rewritten in order to produce a collection of typeC? - Is this a correct way to define a generic method that returns the same collection type (in my case a subtype of
Seq) as input in general?
Scala 2.12.4
What you're asking for can be done using one of the most powerful yet controversial features of the collections library, that is
CanBuildFrom. Here is how:Let's give it a twist in the REPL:
It seems to work.
import scala.language.higherKindsis needed in order to avoid a warning for the higher-kind (C[A]) usage.