通用子类

时间:2017-04-05 20:34:04

标签: scala generics

我有一个带有泛型类型参数的案例类Document。现在我想在运行时获取TypeParamater类型。

我没找到办法。

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

我现在想要找出哪个类型参数在doc。

有人有任何不确定吗?

1 个答案:

答案 0 :(得分:2)

我对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有很多运气。如果这有帮助,请告诉我!