在 Scala 中,如何在上下文中隐式捕获清单?
In Scala, How can Manifest implicitly be caputured in context?
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]
,类型 Manifest[Int]
的 m
被隐式捕获
但是我的自定义 class A,getA[Int]
发出错误
因为cotext中没有隐式变量。
class A 和 Manifest
有什么区别
Scala 编译器知道 Manifest 并施展魔法吗???
比如,为 Manifest 创建一些隐式变量
简短的回答是肯定的。 Manifest
s 是编译器的魔法,Scala 编译器会根据需要自动为类型生成它们的隐式实例。它们用于绕过 JVM 上的类型擦除(在运行时泛型类型被擦除的问题,例如 List[Int]
看起来与 List[String]
相同)。
有关详细信息,请参阅 What is a Manifest in Scala and when do you need it?。
它们现在也已弃用,取而代之的是 TypeTag
s。
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]
,类型 Manifest[Int]
的 m
被隐式捕获
但是我的自定义 class A,getA[Int]
发出错误
因为cotext中没有隐式变量。
class A 和 Manifest
Scala 编译器知道 Manifest 并施展魔法吗???
比如,为 Manifest 创建一些隐式变量
简短的回答是肯定的。 Manifest
s 是编译器的魔法,Scala 编译器会根据需要自动为类型生成它们的隐式实例。它们用于绕过 JVM 上的类型擦除(在运行时泛型类型被擦除的问题,例如 List[Int]
看起来与 List[String]
相同)。
有关详细信息,请参阅 What is a Manifest in Scala and when do you need it?。
它们现在也已弃用,取而代之的是 TypeTag
s。