问题
Why don't type tags work with type aliases. E.g. given
trait Foo
object Bar {
def apply[A](implicit tpe: reflect.runtime.universe.TypeTag[A]): Bar[A] = ???
}
trait Bar[A]
I would like to use an alias within the following method, because I need to type A
around two dozen times:
def test {
type A = Foo
implicit val fooTpe = reflect.runtime.universe.typeOf[A] // no funciona
Bar[A] // no funciona
}
Next try:
def test {
type A = Foo
implicit val fooTpe = reflect.runtime.universe.typeOf[Foo] // ok
Bar[A] // no funciona
}
So it seems I can't be using my alias at all.
回答1:
Use weakTypeOf instead. Reflection internally distinguishes globally visible and local declarations, so you need to treat them differently as well. This wart may be removed in later versions of Scala.
回答2:
Change def apply
declaration:
import scala.reflect.runtime.universe._
trait Foo
object Bar {
def apply[A]()(implicit tpe: TypeTag[A]): Bar[A] = ???
}
trait Bar[A]
class test {
type A = Foo
implicit val foo = typeOf[A]
def test = Bar[A]()
}
来源:https://stackoverflow.com/questions/14678292/type-aliases-screw-up-type-tags