2013-02-03 99 views
2

为什么不能使用类型别名来处理类型标签。例如。鉴于类型别名拧紧类型标签?

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 
} 

所以似乎我根本无法使用我的别名。

回答

1

使用weakTypeOf代替。反思在内部区分了全局可见和局部的声明,所以你需要以不同的方式对待它们。这个疣可能会在更高版本的Scala中被删除。

+0

好的。但是,我是否也需要更改声明网站?因为我似乎没有从由'weakTypeOf'返回到'TypeTag [A]'的类型进行隐式转换。例如。 'found:reflect.runtime.universe.Type; required:reflect.runtime.universe.TypeTag [A]'(当调用Bar [A](fooTpe)') –

+0

好吧,好像我在从手机回答时忽略了一些东西。首先,'typeOf'和'weakTypeOf'的结果是一个'Type',而不是'TypeTag',所以'fooTpe'不适合'Bar.apply'。 –

+0

其次,您可以完全摆脱'weakTypeOf'并将'TypeTag [A]'改为'WeakTypeTag [A]'。之后,它会正常工作。 –

0

更改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]()             
} 
+0

“应用”无关紧要。你的例子似乎工作,因为你将类型别名移动到**类成员级别**('def test'成为'class test')。它似乎破坏作为一种方法本地类型别名莫名其妙 - 很奇怪.... –