2016-12-05 157 views
2

我正在製作一個應用程序,在Solr和Scala中提出請求。 其實,我得到了10個案例類,我在我的請求後實例化。 爲了製作一個通用的應用程序,我嘗試使用參數類型。Scala:參數匹配類型

我的問題:我必須在我的參數類型上進行切換,並且obv不工作(由於擦除)。

見我reflexions &僞代碼:

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 
} 

這裏我映射:

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] 
     } 
} 

我得到了錯誤 「沒有可以T TypeTag」 。我知道它是因爲擦除,但我不知道該怎麼做。

我只是想能夠測試我的參數類型...

謝謝。

+1

我有你要找的feling對於這樣的事情:http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html – Pavel

+0

是的,我知道我需要使用TypeTag。 Probem:我不知道如何使用和實施它... – GreGGus

回答

5

您需要添加約束至T TypeTag方面:

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] 
    } 
} 

您還需要通過TypeTag在通用代碼,使用這種方法:

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 
} 
+0

是的,讓感官。 但我現在得到了這個問題,就像沒有TypeTag已經初始化。 沒有TypeTag可用於T在 > mapsolr [T] .toUseCase(docs)//發送solr文檔來映射 – GreGGus

+0

順便說一句,提供正確的導入會很好。 – ipoteka