从 Seq[T] 中提取类型 T
Extract Type T from Seq[T]
我有一个案例 class,它有两个字段,它们是 Seq[Objects]
。这两个对象属于两种不同的情况 classes.
case class Passport(country: String, name: String)
case class DrivingLicence(code: String, name: String)
case class Docs(passports : Seq[Passport], driv: Seq[DrivingLicence])
val pass1 = Passport("UK", "Michael")
val pass2 = Passport("USA", "Michael")
val driv1 = DrivingLicence("A2", "Mich")
val driv2 = DrivingLicence("A4", "Mich")
val docs = Docs(Seq(pass1,pass2), Seq(driv1,driv2))
我可以生成一个包含所有属性及其类型的地图,如下所示:
val r = currentMirror.reflect(docs)
val mapType = r.symbol.typeSignature.members.toStream
.collect{case s : TermSymbol if !s.isMethod => r.reflectField(s)}
.map(r => r.symbol.name.toString.trim -> r.symbol.typeSignature)
.toMap
println("Map of Types: "+mapType)
输出为:
Map of Types: Map(driv -> Seq[DrivingLicence], passports ->
Seq[Passport])
但我想要的是摆脱Seq部分,并获得内部类型。类似于:
Map of Types: Map(driv -> DrivingLicence, passports -> Passport)
如何访问 Seq[_]
的内部类型?
您可以使用 typeArgs
获取类型参数列表,但它将 return List[Type]
,因此您需要使用 head
获取第一个元素:
r.symbol.typeSignature.typeArgs.head
我有一个案例 class,它有两个字段,它们是 Seq[Objects]
。这两个对象属于两种不同的情况 classes.
case class Passport(country: String, name: String)
case class DrivingLicence(code: String, name: String)
case class Docs(passports : Seq[Passport], driv: Seq[DrivingLicence])
val pass1 = Passport("UK", "Michael")
val pass2 = Passport("USA", "Michael")
val driv1 = DrivingLicence("A2", "Mich")
val driv2 = DrivingLicence("A4", "Mich")
val docs = Docs(Seq(pass1,pass2), Seq(driv1,driv2))
我可以生成一个包含所有属性及其类型的地图,如下所示:
val r = currentMirror.reflect(docs)
val mapType = r.symbol.typeSignature.members.toStream
.collect{case s : TermSymbol if !s.isMethod => r.reflectField(s)}
.map(r => r.symbol.name.toString.trim -> r.symbol.typeSignature)
.toMap
println("Map of Types: "+mapType)
输出为:
Map of Types: Map(driv -> Seq[DrivingLicence], passports -> Seq[Passport])
但我想要的是摆脱Seq部分,并获得内部类型。类似于:
Map of Types: Map(driv -> DrivingLicence, passports -> Passport)
如何访问 Seq[_]
的内部类型?
您可以使用 typeArgs
获取类型参数列表,但它将 return List[Type]
,因此您需要使用 head
获取第一个元素:
r.symbol.typeSignature.typeArgs.head