如何从TypeTag [T]或Scala中的其他任何通用捕获T? [英] How to capture T from TypeTag[T] or any other generic in scala?

查看:374
本文介绍了如何从TypeTag [T]或Scala中的其他任何通用捕获T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发现如何获取最少常见超类型的typeTag 。但是,如何将类型标签的泛型捕获到类型别名中来操作类型本身?

假设 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆