在运行时确定或访问类型变量的具体类型



考虑到以下内容:

trait A
trait Service{
  type tA <: A
  def ping(a:tA)    
}
// implementations
class A1 extends A
class A2 extends A
class ServiceA1{
  type tA = A1
  def ping(a:tA){println("Service for A1")}
}
class ServiceA2{
  type tA = A2
  def ping(a:tA){println("Service for A2")}
}
// a collection of services
val services = Seq(new ServiceA1, new ServiceA2, ....)
// find the service that supports A1
services.find(_.tA =:= A1)

显然上面的代码无法编译。是否有任何方法在运行时确定类型变量的具体类型?

你可以在你的Service trait中添加一个抽象方法(tATag),它返回tA的TypeTag,在ServiceA1ServiceA2中实现它(顺便说一下,你的服务应该扩展Service trait),并在比较时使用它,像这样:

trait Service {
  type tA <: A
  def ping(a:tA)
  def tATag: TypeTag[tA]
}
class ServiceA1 extends Service {
  type tA = A1
  def ping(a:tA){println("Service for A1")}
  def tATag = typeTag[A1]
}
class ServiceA2 extends Service {
  type tA = A2
  def ping(a:tA){println("Service for A2")}
  def tATag = typeTag[A2]
}
// a collection of services
val services = Seq(new ServiceA1, new ServiceA2)
// find the service that supports A1
services.find(s => s.tATag.tpe =:= typeOf[A1])

相关内容

  • 没有找到相关文章

最新更新