I made some simplifications of my original code just to focus on the problem.
I have this set of classes:
abstract class A(n: String){
def name = n
}
abstract class B[T](n: String) extends A(n){
def printT(t: T) = println(t)
}
object B{
def unapply[T](b: B[T]) = Some(b.name)
}
case class C extends B[Int]("integer")
Now I want to discover on a List of As what extends B and then use printT. Something like this:
val list = List(C)
list match{
case b @ B(_) => b.printT(2)
}
On the line case b @ B(_) => b.printT(2) I got:
found : Int(2)
required: T where type T
case b @ B(_) => b.printT(2)
^
Probly this problem would be solved if I could associate the T on the object that I want to use the T of the class. Any way to solve this?
There are a few things wrong with your code.
1) Case classes should be declared with a parameter list:
case class C()2) To instantiate a
C, you need to writeC().List(C)is aList[C.type]butList(C())is aList[C], which is what you want.3)
list matchdoesn’t make sense if your case is aB:listis aList, so it can never be aB. Perhaps you meantlist foreach, which will do the match on each element in the list?Here’s a corrected version of your code that prints
2as expected.Additionally, the
b @ B(_)syntax looks a bit weird to me since there’s no point in extractingBif you’re not going to use its parts. You could, instead, just match on the type: