Scala:获取内部类型的 TypeTag

标签 scala reflection

我正在尝试为内部类型获取 TypeTagClassTag 以向具有类型参数的方法提供 ClassTag。具体来说,我有

trait Baz
trait Foo { type Bar <: Baz }

我想做类似的事情

import scala.reflect.runtime.universe._
import scala.reflect._
typeTag[Foo#Bar] // or maybe
classTag[Foo#Bar]

但我收到“没有可用的类型标签”错误。我的最终目标是为这样的东西提供 ClassTag

import scala.reflect.ClassTag
class Doer[A,B]()(implicit ctA:ClassTag[A], ctB:ClassTag[B])
object Fooer extends Doer[Foo, Foo#Bar]()(classTag[Foo], classTag[Foo#Bar])

最佳答案

通常你可以从内部类型中获取类型标签和类标签。然而,Foo#Bar 是一个抽象类型。类型标签和类标签都不能从抽象类型中获取。您可以获得弱类型标签:

scala> weakTypeTag[Foo#Bar]
res1: reflect.runtime.universe.WeakTypeTag[Foo#Bar] = WeakTypeTag[Foo#Bar]

scala> class Doer[A, B]()(implicit wttA: WeakTypeTag[A], wttB: WeakTypeTag[B])
defined class Doer

scala> new Doer[Foo, Foo#Bar]()
res2: Doer[Foo,Foo#Bar] = Doer@1994551a

关于Scala:获取内部类型的 TypeTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591867/

相关文章:

scala - scala.collection.immutable.Stack.+ : (prepend)? 这里发生了什么

scala - 在 Lift 中,如何在重复(自动复制)CssSel 变换中选择顶级元素

java - 我在 Apache Kylin 中构建 Cube 时遇到错误

scala - 如何让 ensime 显示所有编译错误?

c# - 用于序列化的无参数构造函数与具有默认参数的构造函数相结合,为什么它有效?

java - 使用耳内反射改变静态场

Java : loop on all the classes in the classpath

scala - 动态代理,无需在 scala 中显式指定类型

c# - 在对象初始化之前使用反射设置静态变量值?

c# - 在 .NET 4 应用程序、反射和引用中加载 .NET 4.5.2 程序集