【发布时间】:2022-10-16 12:00:26
【问题描述】:
以下代码示例显示了我的问题的核心:
// This is the base trait that the classes are extending
trait Operation[T] {
def operate(x: T): T
}
// Here are 2 case classes that exist for the sole purpose of being
// the generic type for the classes I'm making
case class CaseClass1(field1_1: String, field1_2: String, field1_3: String)
case class CaseClass2(field2_1: String, field2_2: String, field2_3: String)
// These are the 2 classes that extend my basic trait, implementing the operate
// method with some kind of logic
class FillField1 extends Operation[CaseClass1] {
def operate(input: CaseClass1): CaseClass1 = input.copy(field1_3 = "haha")
}
class FillField2 extends Operation[CaseClass2] {
def operate(input: CaseClass2): CaseClass2 = input.copy(field2_2 = "hoho")
}
import scala.reflect.runtime.universe._
// This is a function that prints out the typetag information currently available
def someFunc[T: TypeTag](x: Operation[T]): Unit = {
println(s"TypeTag is: ${typeOf[T]}")
}
// Here I'm creating a sequence of Operations, but they can have any generic
// type parameter
val someSeq: Seq[Operation[_]] = Seq(new FillField1, new FillField2)
someSeq.map(someFunc(_))
/*
Output:
TypeTag is: _$1
TypeTag is: _$1
*/
someFunc(new FillField1)
/*
Output:
TypeTag is: CaseClass1
*/
如您所见,当我调用someFunc(new fillField1) 时,我可以在运行时正确找到我的类型标签。但是当我使用someSeq,这是一个可以包含多种类型的类的序列时,我无法在运行时获得我需要的类型标签。这是因为您在运行时丢失了该信息吗?
如何在运行时获得正确的类型标签?那么,当我使用Seq[Operation[_]] 时,如何获得TypeTag is: CustomClass1 和TypeTag is: CustomClass2 的输出?
我正在研究一个 Apache Spark 项目,其中我们有一个与此类似的结构,当我使用该序列时,我遇到了一个问题,即 TypeTag 指向一个未知类_$10(或编译器制作的任何名称对于我的类型标签),而不是实际的类型标签 CustomClass1 或 CustomClass2...
【问题讨论】:
-
我猜这是因为
someSeq不保留每个元素的类型。而TypeTag是在编译期间计算的,因此在编译时不可能提供 seq 的每个元素的类型。 -
如果您真的需要它,您可以将
TypeTag存储为CaseClassX类的属性。 -
但是你想达到什么目的?
-
@Kurt 请用磁铁查看更新
标签: scala scala-reflect