【问题标题】:Least common TypeTag from two tags in Scala?Scala中两个标签中最不常见的TypeTag?
【发布时间】:2015-03-11 10:04:31
【问题描述】:

Scala 的 TypeTags 比较容易比较和捕获——但 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

【问题讨论】:

    标签: scala scala-macros


    【解决方案1】:

    Universe 上有一个 lub 方法,它将计算类型列表的最小上限。

    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
    

    从生成的Type 中创建一个TypeTag 似乎有点棘手,但在this answer 中可以看到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-20
      • 2015-06-21
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 2013-06-04
      相关资源
      最近更新 更多