2017-04-05 32 views
1

我有一個具有泛型類型參數的案例類文檔。現在我想在運行時獲得TypeParamater類型。scala TypeTag的通用子類

我沒有找到方法。

def toHtml[T <: DocumentType](doc: Document[T])(variableSubstitution: String => String): String = { 
doc match { 
     case _ : Document[UnStructured] => 
     case _ => // 
    } 
} 

我的文檔類:

final case class Document[T <: DocumentType](chapterList: SortedSet[_ <: ChapterTrait[T]], 
              uniqueId: UUID = UUID.randomUUID(), 
              createDate: DateTime = DateTime.now(), 
              lastEdit: DateTime = DateTime.now(), 
              title: String = "", 
              version: Double = 1.0, 
              designSetting: DocumentDesignSettingTrait = DocumentDesignSetting(), 
              paperFormat: PaperFormat = A4, 
              headerList: List[PageMark] = Nil, 
              footerList: List[PageMark] = Nil, 
              preContent: PreContent = PreContent(), 
              postContent: PostContent = PostContent(), 
              author: Author = Author()) { 

} 

現在類型文​​件

sealed abstract class DocumentType 

sealed abstract class StructuredDocumentType extends DocumentType 

sealed abstract class SemiStructured extends StructuredDocumentType 
//case object SemiStructured extends SemiStructured 

sealed abstract class Structured extends StructuredDocumentType 
//case object Structured extends Structured 

sealed trait UnStructured extends DocumentType 
//case object UnStructured extends DocumentType 

我現在要找出哪些類型參數的文檔爲界。

有人有任何indea嗎?

回答

1

我新望Scala的,但是我覺得你是在爲你的比賽尋找的是類似以下內容:

import scala.reflect.runtime.universe.{TypeTag, typeOf} 

def toHtml[T <: DocumentType](doc: Document[T])(variableSubstitution: String => String)(implicit tag: TypeTag[T]): String = typeOf[T] match { 
    case t if t =:= typeOf[UnStructured] => // ... 
    case t if t =:= typeOf[SemiStructured] => // ... 
    case _ => // ... 
} 

我使用反射API時,我有很多運氣過去用泛型編程。讓我知道如果這有幫助!

+0

謝謝我會嘗試它並儘快報告:) –

+0

@Andréoops我的代碼示例中有一個錯誤!對不起,這個 - 你應該在'T'上匹配,而不是在'doc'上,所以'typeOf [T]匹配{// ...' –

+0

完美!謝謝!!!!! 'docType.tpe匹配{ 情況下若a =:= TYPEOF [非結構化] =>的println( 「丹科」) 情況_ =>的println( 「NEIN」) }' 很高興聽到正確的方式 –