Type aliases screw up type tags?

∥☆過路亽.° 提交于 2021-01-28 03:52:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!