问题描述
发现如何。但是,如何将类型标签的泛型捕获到类型别名中来操作类型本身?
假设 TypeTag [SomeType]
,其中 SomeType
是编译时已知的类型推断的结果(如 t [MyClass1,MyClass2] .common
从)
类型T = ??? //应该是SomeType
即使我的类层次结构将被更改,我也需要它自动获取公共超类型在重构过程中。
如果typeTag的泛型没有被擦除(足以提取常见的超类型类型,编译时间):
class TypeHolder {type T}
object TypeHolder {
def apply [U] (a:TypeTag [U])= new TypeHolder {type T = U}
}
用法:
val typ = TypeHolder(typeTag [Int])
val k:typ.T = 5
val list = List [typ.T]()
trait A {def aaaa:typ.T}
someObject.isInstanceOf [typ.T]
但是你不能用类型变量来做,因为它会被擦除为任何
Found how to obtain typeTag for least common supertype. But how to capture typetag's generic into type alias to operate type itself?
Assuming TypeTag[SomeType]
, where SomeType
is a result of type inference which is known in compile time (like result of t[MyClass1, MyClass2].common
from linked answer)
type T = ??? // should be SomeType
I need it to automatically obtain common supertype even if my class hierarchy will be changed during refactoring.
This will work if typeTag's generic was not erased (enough for extracting common supertype of types, that are known at compilation time):
class TypeHolder { type T }
object TypeHolder {
def apply[U](a: TypeTag[U]) = new TypeHolder{type T = U}
}
Usage:
val typ = TypeHolder(typeTag[Int])
val k: typ.T = 5
val list = List[typ.T]()
trait A { def aaaa: typ.T }
someObject.isInstanceOf[typ.T]
But you can't do it with type variable because it will be "erased" to Any
这篇关于如何从TypeTag [T]或Scala中的其他任何通用捕获T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!