2017-04-05 35 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”) }' 很高兴听到正确的方式 –