Scala:在内部类型上获取TypeTag

Joh*_*van 3 reflection scala

我正在尝试使用TypeTag或者ClassTag为内部类型提供ClassTag带有类型参数的方法.具体来说,我有

trait Baz
trait Foo { type Bar <: Baz }
Run Code Online (Sandbox Code Playgroud)

我想做点什么

import scala.reflect.runtime.universe._
import scala.reflect._
typeTag[Foo#Bar] // or maybe
classTag[Foo#Bar]
Run Code Online (Sandbox Code Playgroud)

但我得到一个'没有打字标签'的错误.我的最终目标是提供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])
Run Code Online (Sandbox Code Playgroud)

rig*_*old 5

通常,您可以从内部类型中获取类型标记和类标记.但是,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
Run Code Online (Sandbox Code Playgroud)