Scala でタプル型をそのコンポーネントの型に分解できますか?
つまり、このようなもの
trait Container {
type Element
}
trait AssociativeContainer extends Container {
type Element <: (Unit, Unit)
def get(x : Element#First) : Element#Second
}
それ自体を解凍することはできませんが、おそらくこれで目的が達成されます。
type First
type Second
type Element = (First, Second)
def get(x: First): Second
これは型をアンパックしませんが、型A
を制約し、 .B
get
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
}
私はこれに少し遅れていますが、パターンマッチングを使用するのはどうですか? 正しい戻り値の型がなく、構文が少しずれている可能性がありますが、次のようになります。
def get[K](key: K): Iterable[Any] {
for ((key, x) <- elements) yield x
}