Reputation: 1286
I'm making an app which make request in Solr with Scala. Actually, i got 10 case class that I instance after my requests. To made an generic app, I try to use parameter type.
My problem : I have to make a switch on my Paramter Type and it's obv not working (due to erasure).
See my reflexions & pseudo code.:
getItem[Apple](10)
=>
def getItem[T](id : Option[Int]) = {
... // Here I request Solr then i want to create my caseClass from Solr docs.
mapsolr[T].toUseCase(docs) // send solr docs to map
}
Here my mapping :
class mapSolr(docs){
def toUseCase[T] = {
// Here i want to be able to make a switch on T
typeOf[T] match {
case x if x =:= typeOf[CaseClass1] =>
blabla // (return List[CaseClass1]
case x if x =:= typeOf[CaseClass2] =>
blabla // (return List[CaseClass2]
}
}
I got the error "No TypeTag available for T". I know its because erasure, but i have no idea how to do.
I just want to be able to test my parameter type ...
Thanks.
Upvotes: 2
Views: 101
Reputation: 1239
You need to add TypeTag context bound to T:
import scala.reflect.runtime.universe._
def toUseCase[T: TypeTag] = {
// Here i want to be able to make a switch on T
typeOf[T] match {
case x if x =:= typeOf[CaseClass1] =>
blabla // (return List[CaseClass1]
case x if x =:= typeOf[CaseClass2] =>
blabla // (return List[CaseClass2]
}
}
You also need to pass TypeTag in generic code that uses this method:
def getItem[T: TypeTag](id : Option[Int]) = {
... // Here I request Solr then i want to create my caseClass from Solr docs.
mapsolr[T].toUseCase(docs) // send solr docs to map
}
Upvotes: 5