我们的库使用 TypeTags,但现在我们需要与另一个需要清单的库进行交互。有没有简单的方法可以从 TypeTag 创建清单?
如果你天真地尝试召唤一个Manifest
when a TypeTag
存在,编译器会给你一个解决方案的提示:
import reflect.runtime.universe._
import reflect.ClassTag
def test[A : TypeTag] = manifest[A]
error: to create a manifest here, it is necessary to interoperate with the type
tag `evidence$1` in scope.
however typetag -> manifest conversion requires a class tag for the corresponding
type to be present.
to proceed add a class tag to the type `A` (e.g. by introducing a context bound)
and recompile.
def test[A : TypeTag] = manifest[A]
^
所以如果你有一个ClassTag
在范围内,编译器将能够创建必要的Manifest
。您有两个选择:
-
添加第二个上下文绑定到任何地方TypeTag
是,如:
def test[A : TypeTag : ClassTag] = manifest[A] // this compiles
-
或者先转换TypeTag
to a ClassTag
,然后要求Manifest
:
def test[A](implicit ev: TypeTag[A]) = {
// typeTag to classTag
implicit val cl = ClassTag[A]( ev.mirror.runtimeClass( ev.tpe ) )
// with an implicit classTag in scope, you can get a manifest
manifest[A]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)