7

Scala でタプル型をそのコンポーネントの型に分解できますか?

つまり、このようなもの

trait Container {
  type Element
}

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

3 に答える 3

3

それ自体を解凍することはできませんが、おそらくこれで目的が達成されます。

  type First
  type Second
  type Element = (First, Second)
  def get(x: First): Second
于 2009-02-23T00:42:10.740 に答える
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
}
于 2010-05-15T21:44:02.550 に答える
0

私はこれに少し遅れていますが、パターンマッチングを使用するのはどうですか? 正しい戻り値の型がなく、構文が少しずれている可能性がありますが、次のようになります。

def get[K](key: K): Iterable[Any] {
  for ((key, x) <- elements) yield x
}
于 2010-05-15T20:53:32.927 に答える