User1291
User1291

Reputation: 8229

Scala - non-generic wrapper for generic classes

Let's say I have a case class

case class Foo[T<:Bar[T]](t:T)

And I have a

case class FooWrapper[T<:Bar[T]](foos:Seq[Foo[T]])

So far, so good.

Unfortunately, I now want to merge two FooWrapprs in an environment where I have no access to the T used to construct them. I.e. attempting something like this:

def merge(fw1:FooWrapper,fw2:FooWrapper) = {
    FooWrapper(fw1.foos ++ fw2.foos)
}

Obviously, the T used to construct fw1,fw2 could be different, which is why this merge fails.

Perhaps I'm just too tired to see the obvious, but what would be the proper way to overcome this limitation? Would having the wrapper class itself implement a merge method work or can I forget about that due to type erasure?

EDIT

I would like a merge method like this:

case class FooWrapper[T<:Bar[T]](foos:Seq[Foo[T]]){
    def merge(other:FooWrapper[T]) = FooWrapper[T](this.foos ++ other.foos)
}

And then

def doSomethingWith(w1:FooWrapper,w2:FooWrapper) ={
    w1.merge(w2)
}

This compiles fine and just might work, but I'm not sure I can rely on its working correctly.

Upvotes: 0

Views: 94

Answers (1)

Aivean
Aivean

Reputation: 10882

You can enforce the equivalence of the types of the fw1 and fw2 like this:

def merge[T](fw1:FooWrapper[T],fw2:FooWrapper[T]) = {
  FooWrapper[T](fw1.foos ++ fw2.foos)
}

Otherwise, please specify what type do you expect as the result of the merge method?

Upvotes: 1

Related Questions