dk14 dk14 - 1 year ago 69
Scala Question

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

Found how to obtain typeTag for least common supertype. But how to capture typetag's generic into type alias to operate type itself?


, where
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.

Answer Source

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} 


val typ = TypeHolder(typeTag[Int])
val k: typ.T = 5
val list = List[typ.T]()
trait A { def aaaa: typ.T } 

But you can't do it with type variable because it will be "erased" to Any

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download