【问题标题】:Unpacking tuple types in Scala在 Scala 中解包元组类型
【发布时间】:2010-10-09 05:37:56
【问题描述】:

我只是想知道,我可以在 Scala 中将元组类型分解为其组件的类型吗?

我的意思是,像这样的

trait Container {
  type Element
}

trait AssociativeContainer extends Container {
  type Element <: (Unit, Unit)
  def get(x : Element#First) : Element#Second
}

【问题讨论】:

    标签: scala types tuples


    【解决方案1】:

    你不能解压,但也许这可以达到你想要的效果:

      type First
      type Second
      type Element = (First, Second)
      def get(x: First): Second
    

    【讨论】:

    • 这是我认为我需要做的,但我想避免,因为这会改变扩展这个特性的类的实现。
    • 另外,这是否意味着即使在子类中元素对也是相同的对?不应该是 Element <: second>
    【解决方案2】:

    这不会解包类型,但会在调用get 时限制AB 类型。

    trait Container {
      type Element
    }
    
    trait AssociativeContainer extends Container {
      type Element <: Tuple2[_, _]
    
      def get[A, B](x: A)(implicit ev: (A, B) =:= Element): B
    }
    

    这看起来很有希望,但在作弊——如果Element 是抽象的,它就不起作用了。

    def Unpack[T<:Tuple2[_, _]] = new {
      def apply[A, B](implicit ev: T <:< (A, B)) = new {
        type AA = A
        type BB = B
      }
    }
    
    trait AssociativeContainer {
      type Element = (Int, String)
      val unpacked = Unpack[Element].apply
      type A = unpacked.AA
      type B = unpacked.BB
    
      1: A
      "": B
      def get(x: A): B
    }
    

    【讨论】:

      【解决方案3】:

      我有点晚了,但是使用模式匹配呢?没有完全正确的返回类型,我的语法可能有点不对,但这里是:

      def get[K](key: K): Iterable[Any] {
        for ((key, x) <- elements) yield x
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-04
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        • 2019-04-20
        • 2021-03-26
        相关资源
        最近更新 更多