Scala的TypeTag相对易于比较和捕获-但是Scala是否提供任何可作用于2个标签的合成功能?例如,我以一种非常通用的方式使用标签(这意味着类型T消失了)。我可以要求Scala为我提供最小公母的TypeTag吗?这似乎是合乎逻辑的,因为编译器和各种编辑器IDE可以轻松做到这一点并显示公共父级。例子:
Class A
Class B extends A
class C extends A
val tagB:TypeTag[_] = implicitly[TypeTag[B]]
val tagC:TypeTag[_] = implicitly[TypeTag[C]]
val res:TypeTag[_] = lcmFunction(tagB,tagC) //not a real function name .. example only
res // yields a TypeTag such that res.tpe =:= TypeTag[A].tpe
上有一种lub
方法Universe
,该方法将计算类型列表的最小上限。
class A
class B extends A
class C extends A
class D extends C
class E extends C
class F extends E
import scala.reflect.runtime.universe._
val a = typeTag[A]
val b = typeTag[B]
val c = typeTag[C]
val d = typeTag[D]
val e = typeTag[E]
val f = typeTag[F]
scala> lub(List(b.tpe, c.tpe))
res17: reflect.runtime.universe.Type = A
scala> lub(List(b.tpe, c.tpe)) =:= a.tpe
res18: Boolean = true
scala> lub(List(e.tpe, f.tpe))
res19: reflect.runtime.universe.Type = E
scala> lub(List(c.tpe, d.tpe, f.tpe))
res21: reflect.runtime.universe.Type = C
从结果中创建TypeTag
出一个结果Type
似乎有些棘手,但是可以从此答案中看到。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句