简体   繁体   English

如何在基类中获取带有参数的类型

[英]How to get a type with parameters inside the base class

Is it possible to get a full type (with type parameters) inside the base class. 是否有可能在基类中获取完整类型(带有类型参数)。 The following example illustrates issue. 以下示例说明了问题。 See TODO: 参见待办事项:

import scala.reflect.api.Types

abstract class BaseClass {
  def getType: Type = ???  //TODO how to implement
}

case class Child1[M](model: M) extends BaseClass

case class Child2(p: Int) extends BaseClass

...

val c1 = Child1("Hello")
val c2 = Child2(10)

val xs = List(c1, c2)

xs foreach { e: BaseClass =>
  println(e.getType) 
}

// out:
// com.project.Child1[java.lang.String]
// com.project.Child2
// ...

You can add a type parameter to the base class: 您可以将类型参数添加到基类:

abstract class BaseClass[A: TypeTag] {
  def getType = s"${getClass.getName}[${typeOf[A]}]"
}

case class Child1[M: TypeTag](model: M) extends BaseClass[M]
case class Child2(p: Int) extends BaseClass[Unit]

...

xs foreach {e => println(e.getType)}

I can propose you next solution: 我可以为您提出下一个解决方案:

trait BaseClass {
  val realType: Any

  def getType: String = realType.toString()
}

case class Child1[M: TypeTag](model: M) extends BaseClass {
  override val realType = typeTag[Child1[M]]

}

case class Child2(p: Int) extends BaseClass {
  override val realType = typeTag[Child2]
}

It produce not exactly the result you want, but pretty close. 它不完全产生您想要的结果,但是非常接近。

val xs = Seq[BaseClass](Child1[String](""), Child2(1))
xs.foreach { e => println(e.getType) }

give next output 给出下一个输出

TypeTag[test.Child1[String]]
TypeTag[test.Child2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM