【问题标题】:Type aliases screw up type tags?类型别名搞砸了类型标签?
【发布时间】:2013-02-05 18:40:34
【问题描述】:

为什么类型标签不能与类型别名一起使用。例如。给定

trait Foo
object Bar {
  def apply[A](implicit tpe: reflect.runtime.universe.TypeTag[A]): Bar[A] = ???
}
trait Bar[A]

我想在以下方法中使用别名,因为我需要输入A 大约两打:

def test {
  type A = Foo
  implicit val fooTpe = reflect.runtime.universe.typeOf[A] // no funciona
  Bar[A]                                                   // no funciona
}

下一次尝试:

def test {
  type A = Foo
  implicit val fooTpe = reflect.runtime.universe.typeOf[Foo] // ok
  Bar[A]                                                     // no funciona
}

看来我根本不能使用我的别名。

【问题讨论】:

    标签: scala reflection scala-2.10


    【解决方案1】:

    改用weakTypeOf。反射在内部区分全局可见和局部声明,因此您也需要区别对待它们。以后版本的 Scala 中可能会移除这个疣。

    【讨论】:

    • 好的。但是我是否也需要更改申报地点?因为我似乎没有得到从weakTypeOf 返回的类型到TypeTag[A] 的隐式转换。例如。 found : reflect.runtime.universe.Type ; required: reflect.runtime.universe.TypeTag[A](调用Bar[A](fooTpe)时)
    • 好吧,我在用手机接听电话时似乎忽略了一些事情。首先,typeOfweakTypeOf 的结果都是Type,而不是TypeTag,所以fooTpe 不适合Bar.apply
    • 其次,您可以完全摆脱weakTypeOf并将TypeTag[A]更改为WeakTypeTag[A]。之后它会正常工作。
    • 好的,当我使用 both weakTypeOfWeakTypeTag 时它可以工作。
    【解决方案2】:

    更改def apply声明:

    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]()                                                 
    }
    

    【讨论】:

    • apply 无关紧要。您的示例似乎有效,因为您将类型别名移至 类成员级别def test 变为 class test)。它似乎以某种方式作为方法本地类型别名被破坏了——非常奇怪....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 2012-03-16
    • 2011-10-01
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多