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

时间:2014-07-01 02:55:10

标签: scala reflection type-variables

鉴于以下内容:

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)

显然以上不会编译。有没有办法在运行时确定类型变量的具体类型?

1 个答案:

答案 0 :(得分:0)

您可以在tATag特征中添加一个抽象方法(Service),该特征会返回tA的TypeTag,并在ServiceA1ServiceA2中实现此方法( btw你的服务应该相应地扩展Service特征)并在比较时使用它,如下所示:

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])
相关问题