解压缩Scala中的元组类型

时间:2009-02-23 00:00:42

标签: scala types tuples

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

我的意思是,像这样的事情

trait Container {
  type Element
}

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

3 个答案:

答案 0 :(得分:3)

你本身无法打开包装,但也许这可以达到你想要的效果:

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

答案 1 :(得分:3)

这不会解压缩类型,但在调用A时会限制Bget类型。

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
}

答案 2 :(得分:0)

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

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