class S
class A extends S
class B extends S
class ClassWithTypeParameter[+T]
val a: ClassWithTypeParameter[S] = new ClassWithTypeParameter[A]
값 a의 type 매개 변수에 사용 된 하위 클래스의 유형을 어떻게 결정할 수 있습니까?스칼라에서 유형 매개 변수의 하위 유형을 결정하는 방법은 무엇입니까?
class S
class A extends S
class B extends S
class ClassWithTypeParameter[+T]
val a: ClassWithTypeParameter[S] = new ClassWithTypeParameter[A]
값 a의 type 매개 변수에 사용 된 하위 클래스의 유형을 어떻게 결정할 수 있습니까?스칼라에서 유형 매개 변수의 하위 유형을 결정하는 방법은 무엇입니까?
지우기 형식으로 인해 수 없습니다. 그러나, 나는 이것을하기위한 당신의 시도가 오해로부터 형성되었다고 주장 할 것입니다.
를 변경할 수없는 형를 가지며,이 하나의 참조, a
이며,이 기준의 유형 ClassWithTypeParameter[S]
이다. 그. 그렇지. 모든. 컴파일러는이 참조로 수행 할 수있는 작업을 알 수 있습니다. 유형은 컴파일러를위한 것입니다. 런타임에, a
에 할당 된 값은 ClassWithTypeParameter[A]
과 관련이 없습니다. 일부 근사 (삭제에 의해 제한)이 일을
한 가지 가능한 방법은 이 (2.10 다른 뭔가라는) 명단 사용하는 것입니다
class ClassWithTypeParameter[+T: Manifest] { def erasure = manifest[T].erasure }
는 그런 다음 erasure
를 호출 할 수있는 너 java.lang.Class
을 얻을 것이다. 내가 말했듯이, 이것은 제한되어 있습니다. 클래스는 유형과 같은 일을하지 않고 구별 할 수있는 방법은 ClassWithTypeParameter[List[Int]]
다음은 나쁜 생각하지만 (대부분의 반사의 사용 등) 작동
ClassWithTypeParameter[List[Double]]
, 예를 들어,이 없다 :
scala> val a: ClassWithTypeParameter[S] = new ClassWithTypeParameter[A]
a: ClassWithTypeParameter[S] = [email protected]
scala> a.paramIs[A]
res0: Boolean = true
scala> a.paramIs[S]
res1: Boolean = false
scala> a.paramIs[B]
res2: Boolean = false
그리고 :
을 우리에게 제공class ClassWithTypeParameter[+T: Manifest] {
def paramIs[V: Manifest] = manifest[T] == manifest[V]
}
scala> val i = new ClassWithTypeParameter[List[Int]]
i: ClassWithTypeParameter[List[Int]] = [email protected]
scala> i.paramIs[List[Int]]
res3: Boolean = true
scala> i.paramIs[List[Double]]
res4: Boolean = false
는 다음을 사용하여 유사한
paramSubtypeOf
및
paramSupertypeOf
방법을 쓸 수
Manifest
의
<:<
및
>:>
.
스칼라 2.10에서
(마일스톤 4 이상)이 유형 얻을 a much more flexible way있어 :
class ClassWithTypeParameter[+T: TypeTag] {
def paramType = reflect.runtime.universe.typeTag[T].tpe
}
지금 당신이 바로 슈퍼 타입을 얻을 수 a.paramType.parents
같은 것들을 쓸 수 등
추가 정보를 제공해 주셔서 감사합니다. –
을하지만 그것은 가능하다 CWTP [List [Int]]와 [CWTP [List [Double]]를 구분하기 위해 매니페스트를 사용하십시오. –
@oxbow_lakes 설명해 주셔서 감사합니다. –