在Scala中,Manifest如何隐含地在上下文中被捕获?

时间:2016-10-30 08:39:12

标签: scala jvm manifest

def getManifest[T : Manifest] = implicitly[Manifest[T]]

class A[T] 
object A {
    def apply[T] = new A[T]
} 
def getA[T : A] = implicitly[A[T]] 

val m = getManifest[Int] 
//res0: Manifest[Int] = Int

val a = getA[Int]
//<console>:14: error: could not find implicit value for evidence parameter of type A[Int] 

即使上下文中没有隐式变量

通过致电getManifest[Int]m类型Manifest[Int]被隐含地加入


但我的自定义类A getA[Int]会发出错误

因为cotext中没有隐式变量。


A类和清单之间有什么区别

Scala编译器是否了解Manifest并做了一些魔术?

就像为Manifest创建一些隐式变量

1 个答案:

答案 0 :(得分:2)

简短的回答是肯定的。 Manifest是编译器魔术,其中Scala编译器会根据需要自动为它们创建类型的隐式实例。他们习惯于在JVM上绕过类型擦除(在运行时泛型类型会被擦除的问题,例如List[Int]看起来与List[String]相同。)

有关详细信息,请参阅What is a Manifest in Scala and when do you need it?

现在也弃用它们,转而使用TypeTags