How to capture T from TypeTag[T] or any other generic in scala?

前端 未结 1 458
野的像风
野的像风 2020-12-22 06:55

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

相关标签:
1条回答
  • 2020-12-22 07:46

    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

    0 讨论(0)
提交回复
热议问题