2014-07-01 8 views
1

에서 형태 변수의 구체적인 유형에 액세스 : 결정 또는 주어진 다음의 런타임

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

유형 소거는 일반적인 경우이 불가능하게 만들지 만 값이'ServiceA1' 인 경우의 예에서 당신은'A1'을 준, 즉'services.find (_. isInstanceOf [서비스 1])'이 효과가있다. – wingedsubmariner

답변

0

당신은 tA의 TypeTag를 반환하여 Service 특성에 추상 메소드 (tATag)를 추가 할 수 있습니다, 그에 따라 (BTW 당신의 서비스가 Service 특성을 확장해야합니다) ServiceA1ServiceA2이를 구현하고 이것을 사용 :

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])