Reputation: 992
as a simplified version of my code:
abstract class GenX
case class X1 extends GenX
case class X2 extends GenX
...
class A {
val ab : LinkedList[X1] = LinkedList()
val ac : LinkedList[X2] = LinkedList()
...
def addX[T <: GenX]( x : GenX, clazz : T) =
getList(clazz) append LinkedList(x) // HERE complains
def getList(T <: GenX) (clazz : T) : LinkedList[_<: GenX] = clazz match {
case X1 => ab
case X2 => ac
...
}
}
my intention is that when a GenX needs to be added to A, it can pass its class as argument for a generic addition like
case class X1 extends GenX{
def addToA(a : A) = a.addX(this, this getClass)
}
the problem now is that compiler complains bout x being of GenX type and not _$1 <: GenX type
I dont get it.
Upvotes: 1
Views: 75
Reputation: 15074
First, with regard to appending, I would suggest using something like a ListBuffer
rather than a LinkedList
, it has a much friendlier API for appending.
Next, your declaration of the clazz
argument declares it to be of type T
(subtype of GenX
), not Class[T]
. You are better off just matching on x
, anyway.
Finally, x
is declared as of type GenX
, and for all the compiler can tell is potentially a different subclass of GenX
from clazz
or the subclass type of the selected list, hence the actual compilation error you would have received.
Here is a version of A that should achieve what you are trying for:
import scala.collection.mutable.ListBuffer
class A {
val ab : ListBuffer[X1] = ListBuffer()
val ac : ListBuffer[X2] = ListBuffer()
// ...
def addX(x: GenX) = x match {
case x1: X1 => ab += x1
case x2: X2 => ac += x2
// ...
}
}
Upvotes: 4