Scala:地图的存在类型 [英] Scala: existential types for a Map

查看:110
本文介绍了Scala:地图的存在类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在未知的A上使用不同类型的地图:

I want to use a map of varying types on an unknown A:

val map: Map[Foo[A], Bar[A]] = ...
...
val foo = new Foo[Qux]
val bar: Bar[Qux] = map(foo)

这不起作用,因为A是未知数.我必须将其定义为:

This doesn't work, because A is an unknown. I have to define it instead as:

val map: Map[Foo[_], Bar[_]] = ...
...
val foo = new Foo[Qux]
val bar: Bar[Qux] = map(foo).asInstanceOf[Bar[Qux]]

这有效,但是演员阵容很丑.我宁愿找到更好的方法.我收集的答案是将现存类型与forSome关键字一起使用,但是我对它的工作方式感到困惑.应该是:

This works, but the cast is ugly. I'd rather find a better way. I gather the answer is to use existential types with the forSome keyword, but I'm confused as to how that works. Should it be:

Map[Foo[A], Bar[A]] forSome { type A }

或:

Map[Foo[A] forSome { type A }, Bar[A]]

或:

Map[Foo[A forSome { type A }], Bar[A]]

推荐答案

实际上,这些都不起作用.

Actually, none of these work.

Map[Foo[A], Bar[A]] forSome { type A }

Map,其中所有键都是相同的Foo[A]类型,并且值是Bar[A]类型(但是对于该类型的不同映射,类型A可能不同);在第二个和第三个示例中,Bar[A]中的AforSome下的A完全不同.

is a Map where all keys are of the same type Foo[A] and values of type Bar[A] (but the type A may be different for different maps of this type); in second and third examples, A in Bar[A] is completely different from A under forSome.

此丑陋的解决方法应该起作用:

This ugly workaround should work:

// need type members, so can't use tuples
case class Pair[A, B](a: A, b: B) {
  type T1 = A
  type T2 = B
}

type PairedMap[P <: Pair[_, _]] = Map[P#T1, P#T2]

type FooBarPair[A] = Pair[Foo[A], Bar[A]]

val map: PairedMap[FooBarPair[_]] = ...

这篇关于Scala:地图的存在类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆